gpt4 book ai didi

java - 扫描仪(System.in) - 无限循环

转载 作者:行者123 更新时间:2023-12-02 04:58:00 27 4
gpt4 key购买 nike

为什么我在递归方法中遇到无限循环,而没有机会输入任何符号来打破它?

class Test {
int key=0;
void meth(){
System.out.println("Enter the number here: ");
try(Scanner scan = new Scanner(System.in)) {
key = scan.nextInt();
System.out.println(key+1);
} catch(Exception e) {
System.out.println("Error");
meth();
}
}
}

class Demo {
main method {
Test t = new Test();
t.meth();
}
}

如果您尝试创建错误(将字符串值放入键中,然后尝试向其添加数字),您将在控制台中看到无限的“错误”文本,而不是在第一个错误之后,程序应该再次询问数量,然后才决定要做什么。

最佳答案

如果nextInt()失败,它会抛出异常,但不会消耗无效数据。来自 documentation :

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

然后,您再次递归调用 meth(),这将尝试再次使用相同的无效数据,再次失败(不使用它),然后递归。

首先,我一开始就不会在这里使用递归。更喜欢简单的循环。接下来,如果您的输入无效,您应该在重试之前适本地使用它。最后,考虑使用 hasNextInt 而不是仅仅使用 nextInt 并捕获异常。

所以也许是这样的:

import java.util.Scanner;

class Test {
public static void main(String[] args){
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the number here:");
while (!scanner.hasNextInt() && scanner.hasNext()) {
System.out.println("Error");
// Skip the invalid token
scanner.next();
}
if (scanner.hasNext()) {
int value = scanner.nextInt();
System.out.println("You entered: " + value);
} else {
System.out.println("You bailed out");
}
}
}
}

关于java - 扫描仪(System.in) - 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28588022/

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