0

Why when the first time process go into the loop, it doesn't stop and wait for user input string first, instead will print out the space and enter? It will only stop on the second time of loop and wait for the user to input something. It's hacker rank 30 Days of code > Day 6 problem by the way.

 public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner stdin = new Scanner(System.in);

    int input;
    input = stdin.nextInt();

    while( input-- >= 0 ){
        String sentence = stdin.nextLine();
        char[] CharArray = sentence.toCharArray();
        for( int i=0; i < sentence.length() ; i=i+2 ){
            System.out.print(CharArray[i]);
        }
        System.out.print(" ");
        for( int i=1; i < sentence.length() ; i=i+2 ){
            System.out.print(CharArray[i]);
        }

        System.out.println();
    }

    stdin.close();
}
Inovramadani
  • 927
  • 10
  • 21

4 Answers4

0

When you enter a number and press enter, nextInt() reads the integer you entered but the '\n' character is still in the buffer, so you need to empty it before entering the loop, so you can simply write : stdin.nextLine() before entering the loop

Omar
  • 721
  • 5
  • 8
0

On first time, you are scanning twice.

input = stdin.nextInt();

it will wait for your input.once you give value it will move ahead. then again

String sentence = stdin.nextLine();

it will take enter(or carriage return) and print that with space.

after this it will work properly

Solution :

use stdin.nextLine(); just after input = stdin.nextInt();

Boola
  • 348
  • 2
  • 14
0

You need to add one more -

stdin.nextLine();

after

input = stdin.nextInt();

without collecting it in some variable. This will consume the newline character appeared just after you finished inputting your integer in below line -

input = stdin.nextInt();

vv88
  • 153
  • 2
  • 14
0

When you enter a number, you also press the ENTER key to enter your input. So the following line consumes the number, but it does not consume the carriage return:

input = stdin.nextInt();

Instead, that carriage return is consumed in the first iteration of the loop by this line:

String sentence = stdin.nextLine();

In other words, it appears from your point of view that the first iteration of the loop did not prompt you for any input, because you unknowingly already entered it. If you want to avoid this, you can add an explicit call to Scanner.nextLine():

input = stdin.nextInt();
stdin.nextLine();
Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263