我正在创建一个小算法,这是其中的一部分。
如果用户输入非整数值,我想输出一条消息让用户再次输入一个数字:
boolean wenttocatch;
do
{
try
{
wenttocatch = false;
number_of_rigons = sc.nextInt(); // sc is an object of scanner class
}
catch (Exception e)
{
wenttocatch=true;
System.out.println("xx");
}
} while (wenttocatch==true);
我遇到了一个永无止境的循环,我不明白为什么。
如何识别用户是否输入了一些非整数?
如果用户输入的是非整数,如何让用户重新输入?
更新
当我打印异常时出现“InputMismatchException”,我该怎么办?
最佳答案
Scanner
在项目被读取之前不会前进。 Scanner JavaDoc 中提到了这一点.因此,您可以使用 .next()
方法读取值,或者在读取 int
值之前检查是否有 hasInt()
。
boolean wenttocatch;
int number_of_rigons = 0;
Scanner sc = new Scanner(System.in);
do {
try {
wenttocatch = false;
number_of_rigons = sc.nextInt(); // sc is an object of scanner class
} catch (InputMismatchException e) {
sc.next();
wenttocatch = true;
System.out.println("xx");
}
} while (wenttocatch == true);
关于Java,用扫描仪尝试捕捉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32592922/