0

With inputs such as; 1 2 3 4, arranged in a column, my code always misses to read the last number. What is wrong? Here is the code:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while(sc.hasNextInt()){
        System.out.println(sc.nextInt());
    }
   sc.close();
}
Win
  • 11
  • 1

1 Answers1

0

The problem is with 'sc.hasNextInt()' Since there isn't another int after the last entry, the program will not print it. If you change the call from 'hasNextInt()' to 'hasNext()' the code should work (as the final newline character will be read).

You'll note that the following code has a blank space at the end of the input string. You could do something similar and use while sc.hasNext(). On the other hand, you could structure your code differently so that you don't print based on the existence of the next character/int in the input string.

import java.util.*;

public class ScannerDemo {

public static void main(String[] args) {

  String s = "Hello World! 3 + 3.0 = 6 ";

  // create a new scanner with the specified String Object
  Scanner scanner = new Scanner(s);

  while (scanner.hasNext()) {
     // check if the scanner's next token is an int
     System.out.println("" + scanner.hasNextInt());

     // print what is scanned
     System.out.println("" + scanner.next());
  }

  // close the scanner
  scanner.close();
  }
}
grill
  • 1,140
  • 1
  • 11
  • 24
  • `sc.hasNextInt()` is called _before_ the last input is read, therefore should return true, and in turn print the last value too. – Mordechai Apr 22 '15 at 19:31
  • That doesn't appear to be the case with the last entry in a string: http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-next-nextint-or-other-nextfoo-methods – grill Apr 22 '15 at 19:35
  • That post isn't related with this problem at all. – Mordechai Apr 22 '15 at 19:40