0

The code below is suppose to start a connect 4 game and I used the scanner class in order to get the user's input but when I run it, it gives me a NoSuchElementError.

I tried to comment out the close(); method and rerun the program but the same error was prevalent.

Heres my code.

Pick a row 
Exception in thread "main" java.util.NoSuchElementException 
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594) 
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at E.start(E.java:223) 
at Main.main(Main.java:6)
public void start(){//need a method that changes the board{
    while(checkPlayerWin()== false|| checkAIWin()== false){
        Scanner scan= new Scanner(System.in);
        System.out.print("Pick a row ");
        int row= scan.nextInt();
        insertCounter(row, "X");
        scan.close();
        reprintBoard();
        random();//insert random counter into a place in the board
        reprintBoard();
    }
}

a.start();//in the class main on line 6
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Jen
  • 1
  • 1
  • 1
    Even if it's not *the* problem, put that call to `close` after the loop and move the `Scanner` declaration before the loop as well. – Federico klez Culloca Jan 18 '23 at 08:56
  • 1
    Do you run this via some kind of online compiler? Those usually have an extra setting to allow input and will default to empty input (which would produce this error or a similar one). – Joachim Sauer Jan 18 '23 at 08:57
  • Yes, I used replit to code this. – Jen Jan 18 '23 at 08:59
  • 1
    Unrelated, but it's good style to avoid comparing your boolean expressions to `true` or `false`: `while (!checkPlayerWin() || !checkAIWin())`. – jsheeran Jan 18 '23 at 09:01
  • 1
    Also, that should be an `&&`, not an `||` – Federico klez Culloca Jan 18 '23 at 09:03
  • 1
    do **not** `close()` a `Scanner` if it is created for reading `System.in`; even not in other methods or code - the `close()` will also close `System.in` and it will not be opened again, so no more data can be read from it, even using a new/other `Scanner` (usually never close a resource that you did not open) – user16320675 Jan 18 '23 at 09:14

0 Answers0