如何在数组列表中获取两个数的和?

huangapple 未分类评论44阅读模式
英文:

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&lt;Integer&gt; numbers = new ArrayList&lt;&gt;();
        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&lt;Integer&gt; a1 = new ArrayList&lt;Integer&gt; ();
a1.add(1);
a1.add(2);

sum = a1.get(0) + a1.get(1);

</details>



huangapple
  • 本文由 发表于 2020年7月26日 19:34:22
  • 转载请务必保留本文链接:https://java.coder-hub.com/63099579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定