For 循环获取用户输入允许您为第一个问题输入两个值,但只计算一个值



我创建了一个小程序,要求用户输入10个随机数,它将打印这些数字的总和。我用一个 for 循环嵌入了它,并包含一个计数器。一切似乎都运行良好,除了当我运行程序时,第一个问题允许我输入两个值,但它仍然只会计算总共 10 个数字。

以下是我目前拥有的,我需要了解第一次提示用户输入号码时出了什么问题:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
boolean hasNextInt = scanner.hasNextInt();
if (hasNextInt) {
sum += numberInput;
} else {
System.out.println("Invalid Number");
}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
}
}

在每个循环中,您都调用scanner.nextInt()scanner.hasNextInt()。但是您没有以有意义的方式使用hasNextInt()的结果(您可能已经注意到,如果您输入不是数字的内容,则不会发生"无效数字"输出(。

第一次调用nextInt()块,直到您输入号码。然后hasNextInt()会再次阻止,因为该号码已经被读取,并且您询问是否会有一个新的号码。下一个数字是从System.in中读取的,但您实际上并没有在此迭代中使用它(您只是询问它是否存在(。然后在下一次迭代中,nextInt()不会阻塞,因为扫描仪已经从System.in中提取了一个数字并且可以立即返回它,因此您看到的所有后续提示实际上都在等待hasNextInt()输入。

这相当于总共 11 个输入事件:前nextInt()加上所有 10 个hasNextInt()

Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
// boolean hasNextInt = scanner.hasNextInt();
//if (hasNextInt) {
sum += numberInput;
//  } else {
//    System.out.println("Invalid Number");
//}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();

不要调用hasnextInt((,它在这里没有用。

它采用了 11 个输入,而不是 10 个。

如果删除此条件,它将需要 10 个输入并正常工作。

您的病情对它没有影响。

最新更新