长卤 2022-09-24 18:05 采纳率: 100%
浏览 26
已结题

Scanner输入异常

本人刚学Java,遇到了一个难以解决的问题
代码如下:
public class test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("输入物品价格");
int prise = sc.nextInt();
System.out.println("价格合理");
} catch (Throwable e) {
e.printStackTrace();
System.out.println("数据不合法");
}
System.out.println("输入a");
int a = sc.nextInt();
System.out.println("输入b");
int b = sc.nextInt();
}
}

img

具体问题:
如果输入的prise为int类型,不触发异常的话,则接下来的代码都能正常运行,如果输入的prise为string类型或者别的类型,在执行了catch内部的语句后,当执行到int a = sc.nextint()时会直接结束进程,具体图片如下:

img

  • 写回答

3条回答 默认 最新

  • aabond 2022-09-24 19:26
    关注

    出现这种情况的原因是因为 scanner.nextInt() 出现异常后不能重新输入, 你需要重新 new 一个 scanner

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 10月3日
  • 已采纳回答 9月25日
  • 创建了问题 9月24日