0

I'm talking about efficiency. I need to read an int from the console input. I know for sure that the input is the form of one int on each line and no other values.

I have a Scanner object defined:

Scanner scan = new Scanner(System.in);

I can either do:

int a = scan.nextInt();

or

int a = Integer.parseInt(scan.nextLine());

Which way is better?

OO7
  • 2,785
  • 1
  • 21
  • 33
Tim Southee
  • 51
  • 2
  • 6
  • My instructor uses the latter method and when I suggested that we can use the more simpler first method, he mentioned some advantage of the second over the first that I don't remember. :( – Tim Southee Mar 23 '15 at 19:21

2 Answers2

0

My assumption is that the second one will use the whole line of input as opposed to the first one which might leave some trash behind which could affect future inputs from the user. In general it is a good practice to clear the input line before requesting more inputs from the user. The first method does not do that therefore you will need another command to do that.

Code Whisperer
  • 1,041
  • 8
  • 16
0

According to the documentation for Scanner.nextInt()

the token is converted into an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Integer.parseInt with the specified radix.

So Integer.parseInt() is called anyway. If you know that each line is already of the form ready to call parseInt immediately, it makes sense to dispense with all those initial checks and just do Integer.parseInt(scan.nextLine()); directly.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116