输入错误,catch 无限循环
来源:互联网 发布:程序员自我评价幽默 编辑:程序博客网 时间:2024/04/28 02:41
我想达到的效果就是,如果输入的不是一个int型,就捕获一个异常并提示用户重新输入,但是实际执行结果是,如果输入了一个错误的id1,就会无限循环catch中的代码,而不会允许再次输入
public static void main(String[] args) {
Random rand = new Random();int randNum = rand.nextInt(101);
boolean isSuccess = false;
System.out.println("我已经随机生成一个了数字,来猜猜这个数字,(^^)");
int times = 0;
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
while (!isSuccess) {
times++;
System.out.print("请输入:");
try {
int in = sc.nextInt();
if (in == randNum) {
isSuccess = true;
System.out.println("恭喜你,答对了,你已经猜了" + times + "次");
} else {
if (in > randNum)
System.out.println("大了,你已经猜了" + times + "次,再猜:");
else
System.out.println("小了,你已经猜了" + times + "次,再猜:");
}
} catch (InputMismatchException e) {
System.out.println("输入错误!");
continue;
}
}
这个问题百度到了,原因是如果不重置Scanner对象sc将会总在while死循环 trycatch,canner对象发生异常后就不能再被使用,所以一直报异常,变成了死循环
改成下面这样:
public static void main(String[] args) {
Random rand = new Random();
int randNum = rand.nextInt(101);
boolean isSuccess = false;
System.out.println("我已经随机生成一个了数字,来猜猜这个数字,(^^)");
int times = 0;
while (!isSuccess) {
times++;
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("请输入:");
try {
int in = sc.nextInt();
if (in == randNum) {
isSuccess = true;
System.out.println("恭喜你,答对了,你已经猜了" + times + "次");
} else {
if (in > randNum)
System.out.println("大了,你已经猜了" + times + "次,再猜:");
else
System.out.println("小了,你已经猜了" + times + "次,再猜:");
}
} catch (InputMismatchException e) {
System.out.println("输入错误!");
}
}
}
好问题解决了。
- 输入错误,catch 无限循环
- scanner 循环输入+错误继续(catch 后 continue)
- 为什么 会出现 输入字母 无限循环的情况呢?
- Linux下输入正确密码无限循环的解决方案
- 解决int型变量cin输入字符无限循环问题
- 无限循环
- C++学习cin.fail()之后无限循环错误说明
- 返回JSON出现Infinite recursion无限循环错误的解决
- java 输入流异常处理并重新输入,无限循环抛异常问题处理
- 处理C++中的错误输入类型导致的无限输入bug
- 循环和catch块
- 无限循环出错原因
- javascript无限循环滚动
- 实现gallery无限循环
- Android Gallery无限循环
- viewpager无限循环
- 无限循环陷阱
- 嵌入式 shell无限循环
- sip服务器判断同一个transaction条件
- python 里面的单下划线与双下划线的区别(私有和保护)
- 安卓资源库
- 排除NSTimer对目标对象的保留
- iTextSharp5.0页眉页脚及Asp.net预览的实现(PDF导出)
- 输入错误,catch 无限循环
- 小程序WXML之条件渲染
- Python串口发送HEX数组
- github学习--本地仓库同步github远程仓库出现的问题
- SpringMVC给控制器添加自定义注解控制访问权限
- Part 7 - Setting an item selected when an asp.net mvc dropdownlist is loaded
- 参数个数可变函数
- 判别学习算法和生成学习算法
- XCode8的一些权限控制,添加以免引起崩溃