gpt4 book ai didi

java - 为什么这种获取用户输入的方法不起作用?

转载 作者:行者123 更新时间:2023-12-01 19:21:08 24 4
gpt4 key购买 nike

我有以下代码,用于让用户输入一个整数,检查以确保输入有效,如果无效,则再次要求输入。当代码运行时,一切正常,直到给出一些无效输入,此时代码循环而不会暂停再次请求输入,直到发生堆栈溢出,我不知道为什么。代码:

//Create the scanner object
private static Scanner in = new Scanner(System.in);

//Function to get input in integer form, complete with exception handling
//A value of -1 means the user is done inputing
public static int getInt()
{
int num;

//Begin try block
try
{
//Get the user to input an integer
num = in.nextInt();

//Make sure the integer is positive. Throw an exception otherwise
if (num < -1)
throw new InputMismatchException();
}

//If an exception occurred during the inputting process, recursively call this function
catch (InputMismatchException e)
{
System.out.println("Error: Input must be a positive integer, or -1.");
System.out.print("Enter a score: ");
num = getInt();
}

//Return the inputed number
return num;
}

最佳答案

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

javadoc 是这么说的,即不是数字的字符串不会自动从输入中删除。手动调用 in.next() 将其丢弃。

关于java - 为什么这种获取用户输入的方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4187854/

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