1

I want to get two string inputs into a string array

String[] b = new String[n]; 

by using scanner but the scanner automatically takes blank value in b[0].i.e. it skips the first loop.

Scanner scn = new Scanner(System.in);
        int no = 0;
        int n = scn.nextInt();
        String[] b = new String[n];

        for (int j = 0; j < n; j++) {
            System.out.println("Enter the string");
            b[j] = scn.nextLine();
        }

the output occurs like

2
Enter

Enter
abc

can anyone suggest me why this problem occurs??

Rustam
  • 6,307
  • 1
  • 21
  • 25
vineeth
  • 571
  • 4
  • 9
  • 25

1 Answers1

2

This is because nextInt() does not read the \n in your input. This is then read by your nextLine()


More explanation,
When you enter a number when prompted by the nextInt() call. You type a number and press Enter This makes your input look like this

10\n

nextInt() reads only the 10 and leaves out \n.

Then, your nextLine() reads only the \n.

This explains your output.
You can get the expected output by having an extra nextLine() after the nextInt().

See this for more information on it.

Community
  • 1
  • 1
Ghazanfar
  • 1,353
  • 12
  • 21