user2770254
user2770254

Reputation: 89

Why is my loop seeming to start at an index of 1?

public static void main(String args[])
{

    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    String[] label = new String[n];
    int[] data = new int[n];
    int x = 0;

    for(x = 0; x < n*2; x++)
    {
        if (x<n)
        {
            label[x] = scan.nextLine();
        }
        if (x >= n)
        {
            data[x-n] = scan.nextInt();
        }
    }   
    System.out.print(data[0]);
}

When I try to input this, for example:

4
one
two
three
four

I get an error at "four." Shouldn't it be putting these string values into the array?

Upvotes: 0

Views: 140

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501926

The problem is that nextInt doesn't consume the line - just the integer. So you're actually getting labels of "", "one", "two" and "three" - and then it's trying to read the "four" as the first data element (with nextInt).

If you type your input like this:

4 one
two
three
four
1 2 3 4

then you'll end up with a label array of {"one", "two", "three", "four"} and a data array of {1, 2, 3, 4}.

Upvotes: 9

Related Questions