gpt4 book ai didi

java - 如何检查用户输入是否不是 int 值

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:04:51 25 4
gpt4 key购买 nike

我需要检查用户输入值是否不是 int 值。我尝试了我所知道的不同组合,但我要么一无所获,要么出现随机错误

例如:

如果用户输入“adfadf 1324”,它会发出一条警告消息。


我有什么:

       // Initialize a Scanner to read input from the command line
Scanner sc = new Scanner(System.in);
int integer, smallest = 0, input;
boolean error = false;

System.out.print("Enter an integer between 1-100: ");
range = sc.nextInt();

if(!sc.hasNextInt()) {

error = true;
System.out.println("Invalid input!");
System.out.print("How many integers shall we compare? (Enter an integer between 1-100: ");
sc.next();
}

while(error) {
for(int ii = 1; ii <= integer; ii++) {

...

} // end for loop
}
System.out.println("The smallest number entered was: " + smallest);

}
}

最佳答案

如果输入无效则抛出异常

Scanner sc=new Scanner(System.in);
try
{
System.out.println("Please input an integer");
//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
//Print "This is not an integer"
//when user put other than integer
System.out.println("This is not an integer");
}

关于java - 如何检查用户输入是否不是 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18119211/

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