1

I recently ran into some trouble with Java's Scanner. When calling methods such as nextInt(), it doesn't consume the newline after pressing Enter. My solution is:

package scannerfix;

import java.util.Scanner;

public class scannerFix {
    static Scanner input = new Scanner(System.in);

    public static int takeInt() {        
        int retVal = input.nextInt();
        input.nextLine();
        return retVal;
    }

    public static void main(String[] args) {
        int num = scannerFix.takeInt();
        String word = input.nextLine();
        System.out.println("\n" + num + "\t" + word);
    }
}

It works, but here's my question: Is this in any way bad?

Tom
  • 14,120
  • 16
  • 41
  • 47
wessltov
  • 67
  • 6
  • 3
    nope, it´s ok as it is one soltution offered by [this question](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – SomeJavaGuy Mar 21 '16 at 12:48

2 Answers2

2

"Enter" is not consumed because it equals "\n" (in Windows / Linux etc) which is a standard delimiter. You already skip to the next line with input.nextLine();
So your solution is fine!

For more info on how delimiters work regarding the Scannerclass see:
How do I use a delimiter in Java Scanner?

Community
  • 1
  • 1
M. Suurland
  • 665
  • 11
  • 30
  • 1
    You explanation is a bit wrong. It has nothing to do with `\n` not being an `int`. What matters is, that it is one of the standard delimiter signs and the they aren't consumed by `nextInt()`. If the delimiter is `"3"` and the input is `"313"` then `nextInt()` would return `1` and keep the second `3` in the stream. – Tom Mar 21 '16 at 13:30
1

One issue is that it can hide some errors in the input. If you expect there to be an integer on one line, and another on the next, but instead the first line contains "2 a" then you will read it as a 2. For some cases, you might want to reject this input instead and display an error.

fgb
  • 17,739
  • 2
  • 33
  • 50
  • 1
    @Tom Thanks, I've fixed the value. – fgb Mar 21 '16 at 13:28
  • That won't be the case in my project. I already have a method in place that keeps asking for an integer until it gets one. All I have to do is edit it slightly – wessltov Mar 21 '16 at 13:29
  • @wessltov And what if the user provides more than one number in one line? Should the other numbers be ignored? – Tom Mar 21 '16 at 13:31
  • @Tom I ask for an int using a println, but I use nextLine() to make sure no errors occur. I then `try` to convert that input to an int. If it fails, it repeats this process. – wessltov Mar 21 '16 at 13:36
  • @wessltov Since you expect only one number per line, you solution is ok. – Tom Mar 21 '16 at 13:45