1

My CS professor recommends using the nextLine() method and parsing out the integer rather than using the nextInt() method. I was just wondering why use nextLine() instead of nextInt().

For Example:

Scanner in = new Scanner(System.in);
System.out.println("Enter an integer: ");
String input = in.nextLine();
int num = Integer.parseInt(input);

Instead of:

Scanner in = new Scanner(System.in);
System.out.println("Enter an integer: ");
int input = in.nextInt();
  • 3
    [This is probably why](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo). That, or the fact that `nextLine()` gives you more control over checking for different types of input. – Mihir Kekkar Sep 25 '19 at 18:22
  • "Gives you more control" would be my guess, at least in the long run. To avoid weird problems that often trip students up, it's probably Mihir's link. – markspace Sep 25 '19 at 18:34

2 Answers2

1

My reasoning would be because students assume the input is just magically read as an int, boolean, long, etc. and skip over the fact of how it actually changes into whatever primitive data type. Other languages (especially Java's counterpart C#) require you to read in the input as a string first and then parse it to the appropriate data type.

There's also the new line character problem with Scanner when using nextInt.

ub3rst4r
  • 2,288
  • 20
  • 33
0

When calling the nextInt() method, the current position of the input stream jumps to the next entered String. And after pressing Enter you manually jump into the next line.

However, when calling the nextLine() method, the input stream instantly jumps to the next Line.

Putting the nextInt() method in a loop may cause the function to read something before being able to type, which is something you don't want.

        Scanner sc = new Scanner(System.in);
        int x;
        do{
            try{
                x = sc.nextInt();
                break;
            }

            catch(InputMismatchException e){
                System.out.print("Enter an Integer");
            }
        }while(true);       

Runs the loop forever, while

        Scanner sc = new Scanner(System.in);
        int x;
        do{
            try{
                x = Integer.parseInt(sc.nextLine());
                break;
            }

            catch(NumberFormatException e){
                System.out.print("Enter an Integer");
            }
        }while(true);       

does not

Ben K
  • 16