2

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.

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah. Stupid mistake. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.