0

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
  • 21
  • 1
  • 1
  • 2

4 Answers4

11

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().

Thats because the Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.

You can fire a blank Scanner#nextLine call after Scanner#nextInt to consume rest of that line including newline

int option = input.nextInt();
input.nextLine();  // Consume newline left-over
String str1 = input.nextLine();
amrender singh
  • 6,982
  • 3
  • 17
  • 25
3

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);

}
  • Thank you..This is working – Sarthak Patil Jul 16 '17 at 02:54
  • 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

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
  • 613
  • 4
  • 19
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
  • 408
  • 5
  • 16