Habbo
Habbo

Reputation: 145

Java: 2D Array with two variables

I have a 2D array. I have the value x and the value y. I want that every x can give a value to each y. So if there are 1x and 2y:

First x, first y: 5 (gives random value)

First x, second y: 3 (3 is a random value)

I want the array to store each value every y has gotten by every x in an array. This is what I got, however it does not work as I want it to:

    int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value to x"));
    int y = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value to y"));
    int[][] array = new int[x][y];
    int counter1 = 0;
    int counter2 = 0;

    while (x > counter1) {
        while (y > counter2) {
            int value = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value x gives to the current y"));
            array[counter1][counter2] = value;
        }
        counter1++;
        counter2 = 0;
    }

As you see, I want x and y to be able to vary. I have tried debugging it, however without any success.

Upvotes: 2

Views: 621

Answers (1)

Eran
Eran

Reputation: 393831

It looks like you forgot to increment counter2. I'd also suggest to change the order of the operands in the while conditions to make your code more readable :

while (counter1 < x) {
    while (counter2 < y) {
        int value = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value x gives to the current y"));
        array[counter1][counter2] = value;
        counter2++; // added
    }
    counter1++;
    counter2 = 0;
}

Of course a for loop would be more readable :

for (int counter1 = 0; counter1 < x; counter1++) {
    for (int counter2 = 0; counter2 < y; counter2++) {
        int value = Integer.parseInt(JOptionPane.showInputDialog(null, "Insert a value x gives to the current y"));
        array[counter1][counter2] = value;
    }
}

Upvotes: 2

Related Questions