Java - 将多个用户输入添加到ArrayList中

3

我试图从用户输入的同一行中读取无限数量的数字(由空格分隔),并打印所有大于0的值的平方 - 所有这些都不使用for循环。

例如...

输入:

1 2 3 4 -10 -15

输出:

30

以下是我目前拥有的代码:

ArrayList<Integer> numbers = new ArrayList<Integer>();

    //insert into array if > 0
    int x = sc.nextInt();
    if(x > 0){
        numbers.add(x);
    }

    //square numbers array
    for (int i = 0; i < numbers.size(); ++i) {
        numbers.set(i, numbers.get(i) * numbers.get(i));
    }

    //sum array
    int sum = 0;
    for(int i = 0; i < numbers.size(); ++i){
        sum += numbers.get(i);
    }
    System.out.println(sum);

正如您所看到的,我只扫描用户的一个输入,因为我不确定如何处理无限的输入。此外,我在我的两个方程式中使用了for循环。

谢谢


你可以使用 split 函数然后进行计算。 - Shubhendu Pramanik
5个回答

2

由于你要加上每个数字的平方,所以你不需要任何列表,只需要一个单独的数字,每次从输入中读取一个数字后,将其平方加到该数字上即可。类似于:

int result = 0;    
Scanner scanner = new Scanner(System.in);

while(scanner.hasNextInt()){
    int num = scanner.nextInt();
    if(num > 0)
        result += num * num;
}

System.out.println(result);

嗨,感谢回复。有两件事...当我运行这个程序并打印/存储输出时,例如I/P: 5 5 5 & O/P: 25 50 75...如何打印/存储平方和,即如上所示的75?另外,如果我输入:1 -1,什么也不会发生。 - 0xgareth

1
作为第一个回答所说,你不需要使用ArrayList。
但是如果你坚持这样做,这里有一个解决方案:
为了存储数字,请使用以下代码:
while(sc.hasNextInt()){
    int x = sc.nextInt();
    if(x > 0){
        numbers.add(x);
    }
}

您可以通过以下方式避免使用for循环:

不要使用如下代码:

for (int i = 0; i < numbers.size(); ++i) {
    numbers.set(i, numbers.get(i) * numbers.get(i));
}

您可以使用:

List<Integer> newNumbers = numbers.stream().map(x->x*x).collect(toList());

嗨,这会产生一个错误:“lambda表达式不能重新声明另一个变量”,并且“toList()方法对于测试类型未定义”。 - 0xgareth
@Gareth 你好,第一个错误是由于lambda中的x引起的,你应该将其重命名为其他名称,例如num->num*num。对于toList错误,请使用import static java.util.stream.Collectors.toList; - MichalH

0
你可以使用数组列表来重构你的程序,方法如下:
ArrayList<Integer> numbers = new ArrayList<Integer>(); 
Scanner in = new Scanner(System.in);
while(in.hasNextInt()){
   int x = in.nextInt();
    if(x > 0){
        numbers.add(x * x);
    }
}
int sum = 0;
for(int i = 0; i < numbers.size(); i++){
    sum += numbers.get(i);
}
    System.out.println(sum);

0

读取行后,您可以使用split进行计算:

        int result = 0;
        Scanner scanner = new Scanner(System.in);

        String a[] = scanner.nextLine().split(" ");

        for (String aa : a) {
            if (Integer.parseInt(aa) > 0) {
                result = result + Integer.parseInt(aa) * Integer.parseInt(aa);
            }
        }
System.out.println(result);

输入:2 3 1 -44 -22

输出:14


0

使用lambda表达式:

    ArrayList<Integer> numbers = new ArrayList<>();

    while (sc.hasNextInt()) {
        int x = sc.nextInt();
        if (x > 0) {
            numbers.add(x);
        }
    }

    int sum = numbers.stream().map(i -> i * i).reduce((xx, yy) -> xx + yy).get();
    System.out.println(sum);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接