【问题标题】:Scanner skipping over user input扫描仪跳过用户输入
【发布时间】:2015-08-03 07:53:32
【问题描述】:

我正在尝试进行国际象棋游戏,并且在某个时刻,用户输入了一个与他们想要移动的棋子相关的数字。我之前有下面代码的简化版本,但我最近决定使用“try”和“catch”语句来捕获 InputMismatchException。这是代码:

int inputexception = 0;

do {

    inputexception = 0;

    try {

        System.out.println("What piece would you like to move?");           
        pieceselectioninput = scan.nextInt();

    } catch ( InputMismatchException e ){

        inputexception = 1;

    }

} while ( inputexception == 1 );

所以一旦我运行这个程序,如果我输入一个非 Int 值,它会一直重复“你想移动哪一块?”一直显示在屏幕上,直到我手动终止程序。

我做错了什么?直到我添加了“try”和“catch”短语之前,情况并非如此。

【问题讨论】:

  • 您可以使用Scanner#nextLine 并尝试检查输入是否与仅数字输入匹配,然后再进行转换
  • 您是否尝试过使用调试器找出问题所在?
  • @Jens 是的,我有。对我来说问题是扫描仪没有等待我回复,我不知道为什么

标签: java exception java.util.scanner


【解决方案1】:

只要 inputexception == 1 运行 while 循环,您在 InputMismatchException 的 catch 块中将 inpuexception 值设置为 1。这使得每次输入非 int 值时循环都会继续。

【讨论】:

  • 是的,我这样做是为了如果它不是'int',用户将不得不再次输入,但扫描仪不允许用户输入另一个片段,它永远持续下去。
【解决方案2】:

您的问题有两种解决方案:

保持nextInt

int inputexception = 0;

do {
   inputexception = 0;

   try {

       System.out.println("What piece would you like to move?");           
       pieceselectioninput = scan.nextInt();

    } catch ( InputMismatchException e ){
        // Get the next line so it won´t repeat forever
        scan.nextLine();
        inputexception = 1;
    }
} while ( inputexception == 1 );

直接使用 nextline 语句进行解析:

int inputexception = 0;

do {

inputexception = 0;

    try {

        System.out.println("What piece would you like to move?");     
        String input = scan.nextLine();
        pieceselectioninput = Integer.parseInt(input);

    } catch ( NumberFormatException e ){
        inputexception = 1;
    }
} while ( inputexception == 1 );

【讨论】:

  • 谢谢!解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-26
  • 2015-12-13
  • 2022-01-07
  • 2013-05-14
相关资源
最近更新 更多