Why do my loops stop early when iterating through and array

So I am trying to iterate through a 4 by 3 array of objects and set the value of each object according to user input, but I've run into a problem where the iteration through the array stop at 6 instead of the total 12. I've tried a few way of writing the iterators but they always fail. This is the code.

Card[][] field = new Card[3][2];
    void setvals(){
        Scanner scanner = new Scanner(System.in);
        for(int row= 0; row < field.length; row++){
            for(int col = 0; col < field[row].length; col++) {
                String input = scanner.nextLine();
                field[row][col] = new Card();
                field[row][col].makeCard(input);
            }
        }
    }

I have also tried <= instead of < but then it gives me array index out of bounds. I have no clue what the problem is.

Upvotes: 0

Views: 59

Answers (2)

Arnav Borborah
Arnav Borborah

Reputation: 11769

Your problem is with the array:

Card[][] field = new Card[3][2];

You want the array to be 4 x 3, then set the dimensions as so:

Card[][] field = new Card[4][3];

The reason your code is not working, is since you currently have a 2 x 3 array, evaluating to 6 iterations. A 4 x 3 array would evaluate to 12 iterations, as you want.

Upvotes: 1

nhouser9
nhouser9

Reputation: 6780

You say:

So I am trying to iterate through a 4 by 3 array of objects...

And here is your array: Card[][] field = new Card[3][2];.

That is not a 4x3 array. It is a 3x2 array, which means there should be 6 iterations in your loop, which is what is happening. There is no error here.

Upvotes: 1

Related Questions