Java 如何对arraylist的所有元素求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21047544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sum all the elements of an arraylist
提问by user3182054
So I'm making a GUI where basically the user inputs a series of numbers into an array list and I'm trying to make it so i can get the sum of all the numbers the add in. Here is what I have :
所以我正在制作一个 GUI,基本上用户将一系列数字输入到一个数组列表中,我正在尝试制作它以便我可以获得添加的所有数字的总和。这是我所拥有的:
sum = 0;
for(int i=0; i<numberlist.size(); i++){
sum += numberlist.get(i);
}
Output.setText("The Sum of all the numbers is " + sum);
}
I get an error message that says:
我收到一条错误消息,内容为:
inconvertable types.
required : int
found: java.lang.string
回答by hichris123
I'm betting you have an ArrayList<String>
. This means that your numbers are stored as a String
. So what you should do is use an ArrayList<Integer>
and then parse the strings you get with Integer.parseInt(yourinputstring)
and then add that to the ArrayList.
我打赌你有一个ArrayList<String>
. 这意味着您的号码存储为String
. 所以你应该做的是使用 anArrayList<Integer>
然后解析你得到的字符串Integer.parseInt(yourinputstring)
,然后将它添加到 ArrayList。
回答by Elliott Frisch
You can use Integer.parseInt(String)like so
你可以像这样使用Integer.parseInt(String)
for (int i=0; i<numberlist.size(); i++){
sum += Integer.parseInt(numberlist.get(i));
}
回答by itasyurt
It seems that your GUI takes user inputs as String list.
您的 GUI 似乎将用户输入作为字符串列表。
In this case Try:
在这种情况下尝试:
sum+=Integer.parseInt(numberlist.get(i));
回答by XWaveX
Just from looking at this snippet, I would assume that you have to convert "numberlist.get(i)" to an int.
仅通过查看此代码段,我会假设您必须将“numberlist.get(i)”转换为 int。
sum = 0;
for(int i=0; i<numberlist.size(); i++){
sum += Integer.parseInt(numberlist.get(i));
}
Output.setText("The Sum of all the numbers is " + sum);
}