public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
while(true) {
keyboard=new Scanner(System.in);//再new一个就好了
try {
double n=keyboard.nextDouble();
break;
} catch(Exception e) {
System.out.println("Error, try again");
}
}
}
nextDouble可能不太好用,不如用nextLine(),然后自己转换成double
import java.util.Scanner;
public class T {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
double n = Double.parseDouble(scanner.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Error, try again");
}
}
}
}
scanner的问题,用scanner.nextDouble() 接收键盘输入一旦出现异常,循环再运行scanner.nextDouble()方法就不再接收键盘输入,不运行inputstream.read()方法,而是直接返回上一次有异常的值,然后继续异常。会无限循环catch块的代码的。
所以不能用scanner转型 要接收后自己转型
while(true){
try{
String s=keyboard.next();
double n = Double.parseDouble(s);
break;
}catch(NumberFormatException e){
System.out.println("Error, try again");
continue;
}
}
进break 跳出循环 不会发生什么了