我希望try-catch循环直到我输入一个正确的整数,但当我输入一个字符串时,我所拥有的是一个无限循环:
public class Main00 {
static Scanner scan = new Scanner(System.in);
static int c = 1;
public static void main(String[] args) {
int num = 0;
while (c == 1) {
try {
System.out.println("enter a number");
num = scan.nextInt();
c = 2;
} catch (Exception e) {
System.out.println("enter a Number please : ");
}
}
答案 0 :(得分:2)
用以下代码替换循环:
while (c == 1) {
try {
System.out.println("enter a number");
num = Integer.parseInt(scan.nextLine());
c=2;
} catch (Exception e) {
System.out.println("enter a Number please : ");
}
}
答案 1 :(得分:0)
尝试类似
的内容try {
System.out.println("enter a number");
num = scan.nextInt();
c = 2;
} catch (Exception e) {
c = -1;
System.out.println("best of luck next time :)");
}
答案 2 :(得分:0)
试试这个
public class Main00 {
static Scanner scan = new Scanner(System.in);
static int c = 1;
public static void main(String[] args) {
int num = 0;
while (c == 1) {
try {
System.out.println("enter a number");
String value = scan.nextLine();
num = Integer.parseInt(value);
c=2;
break;
} catch (Exception e) {
continue;
}
}
答案 3 :(得分:0)
最少使用变量和整数,你真的不需要c
变量。
int num = 0;
Scanner scan = new Scanner(System.in);
while (true) {
try {
System.out.println("Enter a number");
num = Integer.parseInt(scan.next());
break;
} catch (Exception e) {
continue;
}
}
答案 4 :(得分:0)
这是我的解决方案,没有使用异常来验证输入和其他一些优化:
public static void main(String[] args) {
int num;
while (true) {
System.out.println("enter a valid number");
if(scan.hasNextInt()){
num = scan.nextInt();
break;
}else{
scan.next();
}
}
System.out.println("input: " + num);
}
您只需检查下一个值是否为整数,如果是整数,则将其直接放在num
值中。这有利于不使用异常而不需要将String解析为整数。我也改变了while循环,现在你不需要c
变量......这只是令人困惑; - )