目标:判断用户输入的数据是否是数字,如果不是,提示用户重新输入,使用while true循环实现
问题:当输入第一个数据是字符时,catch块捕获到异常执行完catch块后循环输出
“输入的内容包含非数字的字符,请重新输入”
原因:Scanner声明在while循环外,当第一次出现异常后没有清空Scanner中的数据,
解决方法:将Scanner写到循环内声明
package com;
import java.util.Scanner;
public class ExceptionDemo1 {
public static void main(String[] args) {
int a=0;
int b=0;
Scanner sc=new Scanner(System.in);//这里出问题了,声明写到循环内
while(true){
try {
// Scanner sc=new Scanner(System.in);
System.out.println("请输入被除数");
a=sc.nextInt();
System.out.println("请输入除数");
b=sc.nextInt();
} catch (Exception e) {
System.out.println("输入的内容包含非数字的字符,请重新输入");
}
try {
System.out.println("商是"+(a/b));
} catch (Exception e) {
System.out.println("NaN");
}
}
}
}