I'm trying to input a variable into an ArrayList and then add all the elements. How can i do that? The code I开发者_开发技巧 tried is below. Thanks.
ArrayList<String> aListNumbers = new ArrayList<String>();
int abc = 23;
aListNumbers.add("abc");
aListNumbers.add("2");
aListNumbers.add("3");
//Java ArrayList Sum All Elements
int sum = 0;
for(int i=0; i < aListNumbers.size(); i++){
sum = sum + Integer.parseInt(aListNumbers.get(i));
}
System.out.println("Sum of all elements of ArrayList is " + sum);
aListNumbers.add("abc");
Here you aren't adding the contents of the variable named abc
to the list. You're adding the String "abc" to the list. This will cause a NumberFormatException
when the code tries to parse the character string "abc" into a number - because "abc" just isn't a number.
aListNumbers.add(abc);
That's closer to what you want, but it will still complain because the variable abc
isn't a String. Since aListNumbers
expects Strings (as it is an ArrayList<String>
), trying to add anything else will upset the compiler.
aListNumbers.add(Integer.toString(abc));
Will work.
Use an ArrayList<Integer> instead of String?
精彩评论