简体   繁体   中英

how to add variable to array list and then total all the elements of arraylist?

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?

The OP does not know how to code in java. The error is obvious and is not worthy of this site.

BUT!

If you spend the time to type anything - I would rather give an answer. Even though its been a couple of decades since I was in those shoes - I remember very well when a simplest thing makes one stuck for hours if not days - I was fortunate to be coding in the same room with really patient (not just knowledgeable) people. So I am for giving the guy some slack.

and the answer is - definitely use ArrayList<Integer>

but also doing add - don't add("2") - this is adding a string, instead add(2) which adds an integer

and if you really want to parse those strings then you should have String abc="23";

the more valuable bit of info is - find examples - the web is full of them - get your questions answered faster and avoid disdain.

peace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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