要求用户输入值,直到输入整数
我是编程的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
在错误的情况下,你需要清除你输入的字符串(例如,通过nextLine
)。由于它不能被nextInt
返回,它仍然在扫描仪中。您还希望将输出值的行移动到try
,因为当出现错误时您不希望这样做。
东西沿着这些路线:
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;
System.out.println("Value "+ x);
}
catch (Exception e){
System.out.println("error");
if (sc.hasNextLine()) { // Probably unnecessary
sc.nextLine();
}
}
}
}
边注:Java有boolean
,就没有必要使用int
为标志。所以:
boolean flag = false;
和
while (!flag) {
和
flag = true; // When you get a value
你能帮忙吗? –
@MridulMittal:**是**帮助。 –
请帮我看看代码我是一个noob –
当扫描器抛出InputMismatchException时,扫描仪将无法 传递导致该异常的标记。
因此sc.nextInt()
再次读取相同的标记并再次抛出相同的异常。
...
...
...
catch(Exception e){
System.out.println("error");
sc.next(); // <---- insert this to consume the invalid token
}
你可以改变你的逻辑如下图所示:
int flag = 0;
int x = 0;
String str="";
while (flag == 0) {
System.out.println("Enter an integer");
try {
str = sc.next();
x = Integer.parseInt(str);
flag = 1;
} catch (Exception e) {
System.out.println("Value " + str);
}
}
在这里,我们第一次读到来自扫描仪的输入,然后我们正试图解析它如int,如果输入的不是整数值,那么它会抛出异常。在例外情况下,我们正在打印用户输入的内容。当用户输入一个整数时,它将被成功解析,并且标志值将更新为1,并且会导致循环退出。
在一个catch块中,比如你的catch(Exception e){'',''e''拥有关于发生了什么的宝贵信息。使用''e.printStackTrace()''来了解更多。 – f1sh
你的'flag'很伤心,因为它想成为布尔值。 – dly
为什么?请帮助 –