英文:
How to get the sum of two numbers in an array list?
问题
import java.util.ArrayList;
import java.util.Scanner;
public class SecondPlusThird {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
while (true) {
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) {
break;
}
numbers.add(number);
}
System.out.println(numbers.get(1) + numbers.get(2));
}
}
I tried it with System.out.println(numbers.get(1) + numbers.get(2));
But it didn't work. I have to print the sum of the second and third numbers given by the user.
英文:
import java.util.ArrayList;
import java.util.Scanner;
public class SecondPlusThird {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
while (true) {
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) {
break;
}
}
System.out.println(numbers.get();
}
}
I tried it with System.out.println(numbers.get(1)+(2));
But it didn't work. I have to print the sum of the second and third numbers given by the user.
答案1
得分: 0
如果您想要对两个数字求和,我建议您使用一个数组。
ArrayList是动态数组,您并没有充分利用它的潜力,所以不要使用它。
不管怎样,如果您仍然想要这么做。
ArrayList<Integer> a1 = new ArrayList<Integer>();
a1.add(1);
a1.add(2);
sum = a1.get(0) + a1.get(1);
英文:
If you want to do sum of two numbers, i would recommend you to use an array.
Arraylist is dynamic array & you are not utilizing its potential so don't use it.
Anyways, if you still want to do it.
ArrayList<Integer> a1 = new ArrayList<Integer> ();
a1.add(1);
a1.add(2);
sum = a1.get(0) + a1.get(1);
</details>
专注分享java语言的经验与见解,让所有开发者获益!
评论