Scanner抛异常陷入死循环怎么解决

不清的年载 2019-06-06 09:23:56
flag = true; int x; int y; while(flag){ try{ System.out.print("输入X值:"); x = input.nextInt(); System.out.print("输入Y值:"); y = input.nextInt(); flag = false; ic.operation(x,y); }catch(InputMismatchException e){ System.out.println("输入数超出范围,请重新输入"); } finally{ } }
...全文
243 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
木易小次郎 2019-06-12
  • 打赏
  • 举报
回复
楼上正解,关键是需要让scanner.next()来略过当前错误输入,否则就永远无法前进,陷入报错怪圈了。
t1647 2019-06-12
  • 打赏
  • 举报
回复
一般情况下应该把try/catch放在循环外面,报错的话直接结束掉就好; 或者清掉错误的输入,在catch里面加上input.next();
qq_39936465 2019-06-11
  • 打赏
  • 举报
回复
引用 楼主 代清勋 的回复:
flag = true; int x; int y; while(flag){ try{ System.out.print("输入X值:"); x = input.nextInt(); System.out.print("输入Y值:"); y = input.nextInt(); flag = false; ic.operation(x,y); }catch(InputMismatchException e){ System.out.println("输入数超出范围,请重新输入"); } finally{ } }
在catch加一句 input.next();清除上次错误就能继续执行了。

public class test10 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input=new Scanner(System.in);
		boolean flag = true;
		int x;
		int y;
		while (flag) {
			try {
				System.out.print("输入X值:");
				x = input.nextInt();
				System.out.print("输入Y值:");
				y = input.nextInt();
				flag = false;
			} catch (InputMismatchException e) {
				System.out.println("输入数超出范围,请重新输入");
				input.next();
			} 

		}

	}

}
运行结果:

输入X值:aaa
输入数超出范围,请重新输入
输入X值:
huhk 2019-06-06
  • 打赏
  • 举报
回复
看你想怎么搞,可以 break 出来,可以return停止method, 可以System.exit(1); 停止程序。 可以check x 按需求自己选择。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧