• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why Scanner.nextInt() isn't working  RSS feed

 
Johnny Dey
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to use Scanner 's hasNextInt() method to read and display to the console some integers from a text file . The text file has the following content

"a 2 5 9 n 7"

My code is

Scanner s= new Scanner(new File("test.txt"));
while(s.hasNextInt()){
int number=s.nextInt();
System.out.println(number);
}

But when I run the program it simply terminates without displaying anything. However when i replace the first character of the text file with a number, it works fine. What am I doing wrong here? My understanding is that since the first character is a string the nextInt() should throw a InputMismatchException but it isnt.

Sorry that was a mistake. i meant hasNextInt(). Corrected

Edit: if thats the case then what could be a workaround to skip past any string and keep looking for integers?
 
Zachary Griggs
Ranch Hand
Posts: 83
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

What is this line supposed to do?

Are you sure you copied that line down wrong? Because I think you meant to put hasNextInt() there. It doesn't make much sense to have an integer in the while condition.
With hasNextInt(), this code makes sense. The while loop will read in the first information it finds (in this case, "a") and see if it is an integer. It is not, so the condition returns false and then skips the loop.
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use hasNext() in your while loop, get a String token with getNext(), then test whether it's an integer with if (token.matches("\\d+)) {. Note that this will only work for integers, not doubles. Note also that getNext() will not consume the newline character at the line of the line.
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You currently got nothing because the while condition (s.hasNextInt) returns false and the while loop exits. It didn't go to the next value.

If the first value is not an int, your while loop won't work. I suggest you use the hasNext(Pattern p) approach feeding in \\d for digits

 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the first value is not an int, your while loop won't work. I suggest you use the hasNext(Pattern p) approach feeding in \\d for digits

I don't think that will work in this situation. The first token is "a" and hasNext("\\d+") will return false.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!