捕获异常后,如何继续执行Java程序?
我编写了一个程序,要求用户输入一个数字,它将返回该数字除以生成的随机数。但是,如果用户输入像“a”这样的字母,则会捕获异常。
如何让程序在捕获异常后继续执行而不是终止?
do{ //Begin of loop
try{ //Try this code
System.out.println("Enter a number");
double i = read.nextDouble(); //Reads user input
double rn = r.nextInt(10); //Generates random number rn
System.out.println(i + " divided by random number " + rn + " is " + (i/rn));
}catch(InputMismatchException type_error){ //Catches error if there is a type mismatch
//Example error: if user enters a letter instead of a double
System.out.println("Error. You cannot divide a letter by a number!");
break; //break stops the execution of the program
}
//using a continue statement here does not work
}while(true); //Loop forever
最佳答案
继续没有帮助!如果您使用 Scanner 类输入数字,则会出现无限循环,写入“错误。您不能将字母除以数字!”到输出。
您的代码等待双数,但收到一封信。该事件触发异常,代码显示错误消息。但该字母将保留在扫描仪中,因此 nextInt 命令会尝试在下一次迭代中加载相同的字母,而无需等待您输入。
在 catch block 中,您必须使用 read.next() 命令清空扫描器。
Scanner read = new Scanner(System.in);
Random r = new Random();
do { //Begin of loop
try { //Try this code
System.out.println("Enter a number");
double i = read.nextDouble(); //Reads user input
double rn = r.nextInt(10); //Generates random number rn
System.out.println(i + " divided by random number " + rn + " is " + (i / rn));
} catch (InputMismatchException type_error) { //Catches error if there is a type mismatch
//Example error: if user enters a letter instead of a double
System.out.println("Error. You cannot divide a letter by a number!");
// Empty the scanner before the next iteration:
read.next();
}
//using a continue statement here does not work
} while (true); //Loop forever
关于java - 捕获异常后继续执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043340/