简体   繁体   English

如何对arraylist的所有元素求和

[英]How to sum all the elements of an arraylist

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

I'm betting you have an ArrayList<String> .我打赌你有一个ArrayList<String> This means that your numbers are stored as a String .这意味着您的数字存储为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<Integer>然后解析你用Integer.parseInt(yourinputstring)得到的字符串,然后将它添加到 ArrayList。

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));
}

It seems that your GUI takes user inputs as String list.您的 GUI 似乎将用户输入作为字符串列表。

In this case Try:在这种情况下尝试:

sum+=Integer.parseInt(numberlist.get(i));

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);
}

according to error:根据错误:

inconvertable types.不可转换的类型。 required : int found: java.lang.string要求:int 找到:java.lang.string

you defined an ArrayList of String which contains inputed numbers, so to sum these numbers firstly you need to convert the String of number to a number and then sum them:您定义了一个包含输入数字的 String ArrayList,因此要先对这些数字求和,您需要将数字字符串转换为数字,然后对它们求和:

  1. if the values are Integer then try to use Integer.parseInt() or Integer.valueOf()如果值是 Integer 那么尝试使用Integer.parseInt()Integer.valueOf()
  2. if the values are Double then try to use 'Double.parseDouble()' or 'Double.valueOf()'如果值为 Double 则尝试使用 'Double.parseDouble()' 或 'Double.valueOf()'
  3. Long.parseLong() or Long.valueOf() Long.parseLong()Long.valueOf()
  4. more details about number 有关号码的更多详细信息
ArrayList<String> numberlist = new ArrayList<>();
numberlist.add("1");
numberlist.add("2");
numberlist.add("3");
int sum = 0;
for (int i = 0; i < numberlist.size(); i++) {
    sum += Integer.valueOf(numberlist.get(i));
}
Output.setText("The Sum of all the numbers is " + sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM