hDDen
hDDen

Reputation: 155

Displaying reverse numbers array

So I have to write a program that accepts 10 numbers (ints) from the keyboard. Each number is to be stored in a different element of an array. Then my program must then display the contents of the array in reverse order.

int [] array = new int [10];
    for(int i = array.length -  1;i >= 0; i--)
    {
    int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i+1)));
        array[i] = number;

            }
                JOptionPane.showMessageDialog(null, array[i]);


}

I tried to put the JOPtionPane.showMessageDialog outside of the loop but then the program can't find the integer "i". I don't know what to do here :/ Please help :P

Upvotes: 0

Views: 298

Answers (4)

ManoDestra
ManoDestra

Reputation: 6473

You need to enter your data first, then display it thereafter in the order you desire...

int [] array = new int[10];
for (int i = 0; i < array.length - 1; i++) {
    int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i + 1)));
    array[i] = number;
}

for (int i = array.length - 1; i >= 0; i--) {
    JOptionPane.showMessageDialog(null, array[i]);
}

I'd also be tempted to simply construct a StringBuilder for your final results and then just show the message dialog once only, rather than for every element of the array, but that's up to yourself :)

Upvotes: 2

Keision Palms
Keision Palms

Reputation: 1

You need two for loops. The first iterates from 0 to 9 and asks for the number and puts it in the array. The second iterates from 9 to 0 and prints the numbers in the array

Upvotes: 0

Z-DNA
Z-DNA

Reputation: 133

That's because you've declared in in for loop, so it has loop scope. Declare it before loop to reuse it after loop finishes

int i;
for(i = array.length -  1;i >= 0; i--)

After that, you can make another loop:

for(i = 0; i < array.length; i++)

to print it in reverse order.

Upvotes: 0

Guy
Guy

Reputation: 50819

i belongs to the loop scope, that's why you can't use it outside of the loop.

To print the reversed array use another loop

// insert the data to the array
int [] array = new int [10];
for(int i = array.length -  1 ; i >= 0 ; i--) {
    int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i+1)));
    array[i] = number;
}

// print the array
for (int i = 0 ; i < array.length ; ++i) {
    JOptionPane.showMessageDialog(null, array[i]);
}

Upvotes: 1

Related Questions