-1

This is the code :

Scanner s = new Scanner(System.in);
    System.out.print("Enter the number of lines : ");
    int a = s.nextInt();
    String[] array = new String[a];

    for (int i = 0 ; i < array.length; i++) {
        System.out.print("Enter line " + i + " : ");
        array[i] = s.nextLine();
        System.out.println();
   }

After first Run ( If a is set to 4 ) :

Enter the number of lines : 4

Enter line 0 :

Enter line 1 : test1

Enter line 2 : test2

Enter line 3 : test3

it skiped Line 0 by itself.. why ?

XerXes
  • 37
  • 2
  • 11

1 Answers1

2

this cause of unread \n in first line add nextLine() before for loop
assume this input for your program

4\n
test1\n
test2\n
test3\n
test4\n

in line int a = s.nextInt(); you read an Integer from input and a equals 4 but \n still exists in input, readable input change to this

\n
test1\n
test2\n
test3\n
test4\n

after that first time you want to read a line Scanner moving forward in input until reach a \n character, and in your input \n is first character in input so Scanner read empty line, readable input change to this

test1\n
test2\n
test3\n
test4\n

next readLine returns test1 and change input to this

test2\n
test3\n
test4\n
Farnabaz
  • 4,030
  • 1
  • 22
  • 42