gpt4 book ai didi

java - Scanner 类的其他条件困惑

转载 作者:行者123 更新时间:2023-12-02 08:42:06 25 4
gpt4 key购买 nike

请检查else条件的sc.nextLine(),这里我给出10个数字,然后得到它们的和。如果提供任何无效数据(不是 int),它将进入 else 条件。将输入视为 -123d然后它会两次显示无效数据行。如果我将 sc.nextLine() 放在 else 之外,它就可以正常工作。我想知道两次打印背后的逻辑。

导入java.util.Scanner;

public class Main {
public static void main(String[] args) {
int count = 0;
int sum = 0;
Scanner sc = new Scanner(System.in);


while (true) {

System.out.print("Enter number " + (count + 1) + " - ");
boolean isInt = sc.hasNextInt();
if (isInt) {
int num = sc.nextInt();
sum += num;
count++;
if (count == 10) {
break;
}
} else {
System.out.print("Invalid number, put int");

sc.nextLine();

}

// sc.nextLine();
}

System.out.println(sum);
sc.close();
}

}

最佳答案

这个问题由三件事组成:

  • nextInt 仅使用构成下一个整数的字符,仅此而已。
  • nextLine 不断消耗字符,直到到达下一个换行符。它还消耗新行字符
  • hasNextInt 默认将新行视为分隔符。

假设代码已运行到 boolean isInt = sc.hasNextInt(); 行,并且您输入了 d 并按 Enter 键(即循环的第四次迭代) 。此时扫描仪的内部状态可以如下所示:

3 \n d \n
^

\n 表示换行符,^ 表示扫描仪当前正在扫描的位置。最后一次调用 nextInt 消耗了 3,但没有消耗其后的新行,这导致扫描仪处于当前位置。

现在,下一个 token d 被扫描(但没有被消耗!)。它不是 int,因此 hasNextInt 返回 false。您的 else block 将被执行。打印错误消息。 nextLine 消耗所有内容,直到下一个新行字符,包括新行字符,它将指针移动到:

3 \n d \n
^

现在我们处于循环的下一次迭代,下一个标记仍然是d,所以同样的事情再次发生。您的 else block 、运行、打印错误消息、消耗 nextLine 并移动指针:

3 \n d \n
^
<小时/>

将此与 nextLine 位于 else 之外的情况进行比较。这意味着每次调用 hasNextInt 时,指针将始终位于 \n 之后。指针始终会被上一次循环迭代中的 nextLine 移动到 \n 之后。换句话说,循环的每次迭代,您总是消耗数字后面的新行。

关于java - Scanner 类的其他条件困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61318545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com