[英]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.我正在尝试将变量输入到 ArrayList 中,然后添加所有元素。 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.在这里,您没有将名为
abc
的变量的内容添加到列表中。 You're adding the String "abc" to the list.您正在将字符串“abc”添加到列表中。 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.当代码尝试将字符串“abc”解析为数字时,这将导致
NumberFormatException
- 因为“abc” 不是数字。
aListNumbers.add(abc);
That's closer to what you want, but it will still complain because the variable abc
isn't a String.这更接近您想要的,但它仍然会抱怨,因为变量
abc
不是字符串。 Since aListNumbers
expects Strings (as it is an ArrayList<String>
), trying to add anything else will upset the compiler.由于
aListNumbers
需要字符串(因为它是ArrayList<String>
),因此尝试添加其他任何内容都会扰乱编译器。
aListNumbers.add(Integer.toString(abc));
Will work.将工作。
Use an ArrayList<Integer> instead of String?使用 ArrayList<Integer> 而不是 String?
The OP does not know how to code in java. OP 不知道如何在 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>
答案是 - 绝对使用
ArrayList<Integer>
but also doing add - don't add("2")
- this is adding a string, instead add(2)
which adds an integer但也做 add - 不要
add("2")
- 这是添加一个字符串,而不是add(2)
它添加一个 integer
and if you really want to parse those strings then you should have String abc="23";
如果你真的想解析这些字符串,那么你应该有
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.更有价值的信息是- 查找示例 - web 充满了它们 - 更快地回答您的问题并避免轻视。
peace和平
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.