gpt4 book ai didi

java - isDigit 验证

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

我正在尝试验证 1 或 2 的输入。但是,使用此代码,如果您输入字母,则会导致程序崩溃。

如何解决这个问题?

System.out.print("Choice: ");
userSelection = keyboard.nextInt();

while (flag == 0)
{
if (userSelection == 1 || userSelection == 2)
{
flag = 1;
}
if(Character.isDigit(userSelection))
{
flag = 1;
}
else
{
flag = 0;
}
if (flag == 0)
{
//this is a system clear screen to clear the console
System.out.print("\033[H\033[2J");
System.out.flush();

//display a warning messege that the input was invalid
System.out.println("Invalid Input! Try again, and please type in selection 1 or selection 2 then hit enter");
System.out.print("Choice: ");
userSelection = keyboard.nextInt();
}
}

最佳答案

nextInt 期望用户输入一个整数。否则将会失败。

您可能想要使用 nextLine 构造一些内容(它读取一行输入,然后您可以检查它, reading single characters as they are being typed is tricky in Java )。

关于java - isDigit 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35353573/

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