The reason for the exception is that you call keyIn.close() after using the scanner once, which not only closes Scanner , but also System.in . In the very next iteration, you create a new Scanner that explodes quickly because System.in now closed. To fix this, you only need to create a scanner before entering the while and skipping the close() call completely, since you do not want to close System.in .
After fixing that the program will still not work due to string comparisons == and != . When comparing strings in Java, you should use equals() to compare the contents of the string. When you use == and != , You are comparing object references, so these comparisons will always return false in your code. Always use equals() to compare strings.
while (!quit){ Scanner keyIn = new Scanner(System.in); String c = "x"; while (!c.equals("y") && !c.equals("n")) { c = keyIn.next(); } if (c.equals("n")) quit = true; }
source share