我是编程的noob。 我想写一个编码的代码,要求用户输入值,直到输入一个整数。要求用户输入值,直到输入整数
public class JavaApplication34 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int flag = 0;
while(flag == 0) {
int x = 0;
System.out.println("Enter an integer");
try {
x = sc.nextInt();
flag = 1;
} catch(Exception e) {
System.out.println("error");
}
System.out.println("Value "+ x);
}
}
}
我认为的代码是正确的,它应该问我,如果我已经进入不是整数以外的任何重新输入值。 但是,当我运行它,并说我输入xyz 它迭代无限时间没有要求我输入值。
test run :
Enter an integer
xyz
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
Enter an integer
error
Value 0
在一个catch块中,比如你的catch(Exception e){'',''e''拥有关于发生了什么的宝贵信息。使用''e.printStackTrace()''来了解更多。 – f1sh
你的'flag'很伤心,因为它想成为布尔值。 – dly
为什么?请帮助 –