(初学者)多次使用扫描仪时,为什么在代码中始终出现“无此类元素异常”的问题

时间:2019-02-17 21:14:08

标签: java

我正在写一个简单的井字游戏,即玩家对电脑。对于我的方法playerMakeTurn,我希望玩家首先输入他们将要移入的行,然后输入该行中的列。但是,我不断收到以下信息:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at TicTacToe.playerMakeTurn(TicTacToe.java:62)
    at TicTacToe.main(TicTacToe.java:17)

我尝试实现hasNextInt(),但是我的实现很可能不正确。

 public static String[][] playerMakeTurn (String[][]playGrid)
    {
       boolean validMove = false;
       Scanner in = new Scanner (System.in);
       while (validMove != true)
       {
        System.out.println("Make your move: enter row number (top to bottom; 1-3)"); 
        int rowMove = in.nextInt() - 1; 
        System.out.println("Make your move: enter column number for row " + (rowMove + 1) + ": (left to right; 1-3)");
        int colMove = in.nextInt() - 1; 
        if (playGrid[rowMove][colMove] == "-");
         {
            playGrid[rowMove][colMove] = "X";
            validMove = true;
         }
       }
      return playGrid;
    } 

我希望它打印出第一条语句,然后输入行值。然后打印下一个,然后输入列值。我已经读过类似的答案,但坦率地说,我不理解它们。正确的代码版本是什么样的。

1 个答案:

答案 0 :(得分:0)

此代码可以正常工作,您的问题必须在所示代码之外。 我制作了一个执行代码的MVCE(请参阅下文),并且在运行时它不会引发您的异常(我尝试了全部9个输入)。

import java.io.*;
import java.util.*;
public class Test {
   public static void main(String[] args) {
      playerMakeTurn(new String[3][3]);
   }
   public static String[][] playerMakeTurn (String[][]playGrid)
   {
       boolean validMove = false;
       Scanner in = new Scanner (System.in);
       while (validMove != true)
       {
        System.out.println("Make your move: enter row number (top to bottom; 1-3)");
        int rowMove = in.nextInt() - 1;
        System.out.println("Make your move: enter column number for row " + (rowMove + 1) + ": (left to right; 1-3)");
        int colMove = in.nextInt() - 1;
        if (playGrid[rowMove][colMove] == "-");
         {
            playGrid[rowMove][colMove] = "X";
            validMove = true;
         }
       }
      return playGrid;
    }
}