【问题标题】:How to prevent user Input from being carried over when exception is thrown?抛出异常时如何防止用户输入被结转?
【发布时间】:2019-09-12 08:38:17
【问题描述】:

我不知道是不是睡眠不足,但我就是不明白为什么会这样。

我的代码要求用户提供int 值。如果用户输入一些愚蠢的东西,比如“二十七”而不是任何数字,它会抛出一个InputMismatchException 异常。这一切都很好。

由于某种原因,用户输入的值被传递到我的代码中,之后一切都搞砸了……

case 'r':
     System.out.print("What height to reap at  : ");
         try {
             reapAt = keyboard.nextInt();
             canadaforestservice.reapTrees(initTreeHeight, initTreeGrowPerYear, reapAt);
             } catch (InputMismatchException e) {
             System.out.println("ERROR: Invalid height");
             }
             System.out.println();
             System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it : ");
             menuItems = keyboard.next().charAt(0);
             break;

预期结果:

(D)isplay, (N)new, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it : r

收获的高度:二十七

错误:无效高度

(D)isplay, (N)new, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :


我的结果:

(D)isplay, (N)new, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it : r

收获的高度:二十七

错误:无效高度

(D)isplay, (N)new, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it : 错误: 选项无效,重试 “字母 T 从之前的用户输入中继承”

(D)isplay, (N)new, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :

【问题讨论】:

    标签: java object exception methods


    【解决方案1】:

    catch (InputMismatchException e) 内添加以下行:keyboard.nextLine(); 以完成对该行的读取:

             // ...
             } catch (InputMismatchException e) {
               System.out.println("ERROR: Invalid height");
               keyboard.nextLine();
             }
             // ...
    

    您可能想了解Scanner#nextInt() 之间的区别

    将输入的下一个标记扫描为int

    Scanner#nextLine()哪个

    使扫描器前进越过当前行并返回 被跳过了

    【讨论】:

      猜你喜欢
      • 2018-12-23
      • 1970-01-01
      • 2019-12-18
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多