4

ı am new in java.here is my code. I determined my String array size with nextint metod using Scanner. Then ı have added Strings with nextline metod. it seems correct for me but ı cant see my first value of array. 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]);

    }
}
berione
  • 122
  • 10
  • I am voting to re-open the question, because the Q&A selected for a duplicate is a poor fit here. This question is about a very specific problem; the duplicate, on the other hand, is a self-answered question that covers all aspects of `Scanner` in tutorial style, and it does not address this specific problem directly. – Sergey Kalinichenko Jan 10 '16 at 11:34

2 Answers2

5

You can see the first entry, it just happens to be a blank String.

The reason this happens is that when you call int n = sc.nextInt(); and user presses Enter, the Scanner reads the integer, but leaves the end-of-line character in the buffer.

When you read the first string with sc.next() the end-of-line "leftover" gets scanned right away, and gets presented to your program as the first String which is blank.

The fix to this problem is simple: call sc.next() after sc.nextInt(), and ignore the result.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-1

Instead of

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]);

This is a bug that occurs when using nexLine() after nextInt() because nextInt() doesn't pull the \n from the input stream buffer, so when you invoke nextLine() it consumes just the \n character (nextLine() is implemented to consume characters until it meets a \n)

Massi A
  • 30
  • 5
  • 2
    Please explain why this does what's expected, as it's not immediately obvious. Also, please explain why you're assigning it, when the typical response is to simply ignore the junk data. – Nic Jan 09 '16 at 23:31