2

I am not able to use nextLine method after using nextInt method.This is the note given below....

note in hacker rank:(If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty). The nextLine method is not getting skiped but it is empty. Code:

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d=scan.nextDouble();
    String s=scan.nextLine();
    // Write your code here.

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
  }
}

Output: String: Double: 3.1415 Int: 42

Sarthak Patil
  • 41
  • 1
  • 1
  • 3

4 Answers4

21

In Scanner class if we call nextLine() method after any one of the seven nextXXX() method then the nextLine() doesn’t not read values from console and cursor will not come into console it will skip that step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().

That's because the Scanner class' nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner class' nextLine().

You can fire a blank Scanner class' nextLine() call after Scanner#nextInt to consume the rest of that line including newline

int option = input.nextInt();
input.nextLine();  // Consume newline left-over
String str1 = input.nextLine();
jdk
  • 451
  • 1
  • 6
  • 18
amrender singh
  • 7,949
  • 3
  • 22
  • 28
6

You may try this.

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        double y = sc.nextDouble();
        sc.nextLine();
        String s = sc.nextLine();

        System.out.println("String: " + s);
        System.out.println("Double: " + y);
        System.out.println("Int: " + x);

}
  • 1
    Explanation: A newline character is leftover from sc.nextDouble so sc.nextLine() is needed to skip over this blank line before assigning s to sc.nextLine() which is the line that contains the data we want. – Rich Nov 05 '19 at 04:21
1

When you are entering the integer for nextInt() then immediate you pres enter key and this enter key caught by nextLine(). s stores enter and that is known as whitespace so it not shows.

ritesh9984
  • 418
  • 1
  • 5
  • 17
0

Yes it reads the remaining line which is empty. So while giving input pass whitespaces you will see the output, instead of printing string print it's length

Kulbhushan Singh
  • 627
  • 4
  • 20