I have two blocks of code here. One scanner properly waits user input, and the other just blows right through it and calls nextInt() which returns a NoSuchElementException. Here is the block that works:
public void startGame() {
out.println("Player1: 1 for dumb player, 2 for smart player, 3 for human player.");
Scanner scan = new Scanner(System.in);
p = scan.nextInt();
if (p == 1)
p1 = new DumbPlayer("ONE");
if (p == 2)
p1 = new SmartPlayer("ONE");
else
p1 = new HumanPlayer("ONE");
out.println("Player2: 1 for dumb player, 2 for smart player, 3 for human player.");
p = scan.nextInt();
if (p == 1)
p2 = new DumbPlayer("TWO");
if (p == 2)
p2 = new SmartPlayer("TWO");
else
p2 = new HumanPlayer("TWO");
scan.close();
And here is the block that does not:
public int findBestMove(Set<Integer> moves, Board b) {
Set<Integer> set = new HashSet<Integer>();
out.println("Player " +name+ ", select a column from 1-7: ");
Scanner scan = new Scanner(System.in); <--here it should wait for input, but does not!
int move = scan.nextInt(); <-- NoSuchElementException
scan.close();
for (int x = 1; x <= 7; x++) {
set.add(move);
move += 7;
}
....etc
Both of these are separate classes, and are called from a main method in yet another class. Basically main() calls startGame(), which in turn calls the findBestMove() method of some Player class…which is where the non-working code resides. Are there times in the program where it is not appropriate to take input? I was under the impression that anytime I wanted user input, I could use this approach. Thanks!
According to the java.util.Scanner javadoc,
Scanner.close()closes the associated stream if this stream implements theCloseableinterface.java.lang.System.inis an InputStream, which implements theCloseableinterface. Hence, after callingScanner.close()on aScannerwhich is associated withSystem.in, theSystem.instream is closed and not available anymore.The following SSCCE works for me. I have removed some code from the question which is not relevant to the actual issue. Note that with this approach, while it works, Eclipse gives me the warning
"Resource leak: 'scan' is never closed", so a better solution would be to use one Scanner instance only.