Using Scanner.next () to enter text

I am trying to get keyboard text input in Java 6. I am new to the language, and whenever I run the following code, I get this error:

package test1; import java.util.Scanner; public class Test { public static void main(String[] args) { boolean quit = false; while (!quit){ Scanner keyIn; String c = "x"; while (c != "y" && c != "n") { keyIn = new Scanner(System.in); c = keyIn.next(); keyIn.close(); } if (c == "n") quit = true; } } } Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:838) at java.util.Scanner.next(Scanner.java:1347) at test1.Test.main(Test.java:11) 

Am I using the next () method incorrectly? I thought he would wait for user input, but it looks like it is not, and throws an exception, saying that there is nothing left in the scanner.

+4
source share
4 answers

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; } 
+8
source

To evaluate strings you should use .equals

while (! c.equals ("y")) {do stuff ...

+2
source
  • declare a link to the scanner outside of your loops. you do not need to create it and close it every time.

  • compare the string text with the equals method, and not with the == operator.

+1
source

Try using nextLine () and look only at the first element in the returned string.

The! = And == will only work when used against characters or other primitive types that will only work in C #. You will need to use .equals to make sure you check for the correct equality.

0
source

All Articles