The first value of the array

I am new to java.here - my code. I determined the size of the String array using the nextint method using Scanner. Then ı added lines with the following method. this seems right to me, but I don't see my first array value. what is the problem in this code.

public class App {   
    public static void main(String[] args) {
        String[] arr;
        Scanner sc = new Scanner(System.in);
        System.out.println("write a number ");
        int n = sc.nextInt();
        arr = new String[n];

        for (int i = 0; i < n; i++) {

            arr[i] = sc.nextLine();

        }
        System.out.println(arr[0]);

    }
}
+4
source share
2 answers

You can see the first entry, it is just empty String.

The reason for this is that when you call int n = sc.nextInt();, and the user presses Enter, Scannerreads an integer, but leaves the end of line character at the end.

sc.next(), "leftover" String, .

: sc.next() sc.nextInt() .

+5

for (int i = 0; i < n; i++) { arr[i] = sc.nextLine(); } System.out.println(arr[0]);

Do

arr[0] = sc.nextLine();
for (int i = 0; i < n; i++) { arr[i] = sc.nextLine(); } System.out.println(arr[0]);

, nexLine() nextInt(), nextInt() \n , nextLine() \n ( nextLine() , \n)

-1

Source: https://habr.com/ru/post/1623603/


All Articles