-1

I was solving this hackerrank 30 days of code challenge. The code is below:

import java.util.*;

public class jabcexample1 {
    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";

        /* Declare second integer, double, and String variables. */
        try (Scanner scan = new Scanner(System.in)) {
            /* Declare second integer, double, and String variables. */
            int i2;
            double d2;
            String s2;

            /* Read and save an integer, double, and String to your variables.*/
            i2 = scan.nextInt();
            d2 = scan.nextDouble();

            scan.nextLine(); // This line
            s2 = scan.nextLine();

            /* Print the sum of both integer variables on a new line. */
            System.out.println(i + i2);

            /* Print the sum of the double variables on a new line. */
            System.out.println(d + d2);

            /* Concatenate and print the String variables on a new line;
            the 's' variable above should be printed first. */
            System.out.println(s.concat(s2));
        }
    }
}

In this code I added an extra line scan.nextLine(); because without it the compiler doesn't even notice the next line that is s2 = scan.nextLine();. Why compiler doesn't notice s2=scan.nextLine(); without writing scan.nextLine();?

Sefe
  • 12,811
  • 5
  • 36
  • 50

1 Answers1

3

This has nothing to do with the compiler and everything with how Scanner behaves.

If you read the Java docs you will see Sanner.nextLine() does

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Now you may be wondering what is left after you called

i2 = scan.nextInt();
d2 = scan.nextDouble();

In this case it is the carriage return characters. Calling scan.nextLine() reads those character and sets the position to the beginning of the next line.

Leon
  • 10,717
  • 4
  • 31
  • 54