Using Scanner.Nextline()

Using scanner.nextLine()

I think your problem is that

int selection = scanner.nextInt();

reads just the number, not the end of line or anything after the number. When you declare

String sentence = scanner.nextLine();

This reads the remainder of the line with the number on it (with nothing after the number I suspect)

Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.

What's the difference between next() and nextLine() methods from Scanner class?

I always prefer to read input using nextLine() and then parse the string.

Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.

A useful tool for parsing data from nextLine() would be str.split("\\s+").

String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces

For more information regarding the Scanner class or String class refer to the following links.

Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Why scan.next() + scan.nextLine() instead of scan.nextLine()

Reg. Scanner javadoc

next() - Finds and returns the next complete token from this scanner.

nextLine() - Advances this scanner past the current line and returns the input that was skipped.

So, with next() basically it reads only first word, only 1st token (string) is being taken (remaining things are stored in the buffer, but nextLine() allows you to read until enter is pressed= whole line.

Difference can be seen if you will try following snippet and try to put combinations of words and sentences:

Scanner sc = new Scanner(System.in);
System.out.println("first input:");
String tmp = sc.next();
System.out.println("tmp: '" + tmp +"'");
System.out.println("second input:");
tmp = sc.next() + sc.nextLine();
System.out.println("2nd tmp: '" + tmp +"'");
}

Inputs and outputs:

first input:
firstWord
tmp: 'firstWord'
second input:
second sentence
2nd tmp: 'second sentence'
//-------------
first input:
first sentencemorewords
tmp: 'first'
second input:
2nd tmp: 'sentencemorewords'

Maybe better explanation comes with direct printing:

Scanner sc = new Scanner(System.in);
System.out.println("first input:");
String tmp = sc.next();
System.out.println("tmp: '" + tmp +"'");
System.out.println("second input:");
System.out.println("next: " + sc.next() +",... nextLine: " + sc.nextLine());

Notice, only first word is handled by first sc.next(), in case of more words any other word will be handled by second sc.next(), but in case of more than 2 words, remaining string will be handled by nextLine

first input:
first second third more words
tmp: 'first'
second input:
next: second,... nextLine: third more words

So in your program if you need only one word, use sc.next(), if you need to read the whole line, use nextLine()

Scanner is skipping nextLine() after using next() or nextFoo()?

That's because the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine returns after reading that newline.

You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself).

Workaround:

  • Either put a Scanner.nextLine call after each Scanner.nextInt or Scanner.nextFoo to consume rest of that line including newline

    int option = input.nextInt();
    input.nextLine(); // Consume newline left-over
    String str1 = input.nextLine();
  • Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. For example, you may convert to an integer using Integer.parseInt(String) method.

    int option = 0;
    try {
    option = Integer.parseInt(input.nextLine());
    } catch (NumberFormatException e) {
    e.printStackTrace();
    }
    String str1 = input.nextLine();

Scanner nextLine() issues

I think you're overcompensating with too many nextLines. You may want to do that once to clear the line after the int is inputted, for example, to clear the newline, but the second time here just absorbs an extra line of input:

System.out.println("You have not entered a valid number. Please enter a real number this time.");
in.nextLine();//first time
}
}
in.nextLine();//this second time is unnecessary.

The same thing happens with your duplicate uses here:

in.nextLine();
firstLetter = in.nextLine();
break;

You should only add an extra in.nextLine() immediately between inputting nextSOMETHINGELSE() and another nextLine().

EDIT:

Additionally, note that whenever you call in.nextLine(), you are absorbing a line of input. For example, this line should be fixed:

        if(in.nextLine().length() > 1){

because it reads in a line, using it up, and then checks whether that (now used-up) line is long enough.

Can't use Scanner.nextInt() and Scanner.nextLine() together

The problem is the '\n' character that follows your integer. When you call nextInt, the scanner reads the int, but it does not consume the '\n' character after it; nextLine does that. That is why you get an empty line instead of the string that you were expecting to get.

Let's say your input has the following data:

12345
hello

Here is how the input buffer looks initially (^ represents the position at which the Scanner reads the next piece of data):

1  2  3  4  5 \n h  e  l  l  o \n
^

After nextInt, the buffer looks like this:

1  2  3  4  5 \n h  e  l  l  o \n
^

The first nextLine consumes the \n, leaving your buffer like this:

1  2  3  4  5 \n h  e  l  l  o \n
^

Now the nextLine call will produce the expected result. Therefore, to fix your program, all you need is to add another call to nextLine after nextInt, and discard its result:

k = in.nextInt();
in.nextLine(); // Discard '\n'
input = in.nextLine();

Java How to get scanner.nextLine() on the same line?

Try:

   System.out.print("--Television Show or Film (t or f): ");
String type = input.next();


Related Topics



Leave a reply



Submit