1

I'm doing a foundations course on Java, and the task is to create a program where a user inputs 10 strings into an array, the have the program display them back to the user in the reverse order of which they were input.

Here is the relevant code so far

String []stringarray = new String[10];

public void add()
{
    System.out.println ("Enter 10 Strings :");
    for ( int i=0; i<10  ; i++ )
        stringarray[i] = Genio.getString(); 
}

public void display()
{
    for (int i=0; i<10/2; i++)
    {
        String tmp = stringarray[i];
        stringarray[i] = stringarray[10 - i - 1];
        stringarray[10 - i - 1] = tmp;
        System.out.println (stringarray[i]);
    }
}

So when I input, 1 2 3 4 5 6 7 8 9 0, I should receive 0 9 8 7 6 5 4 3 2 1 back.

However I only receive 0 9 8 7 6. I think it might be to do with the "i<10/2;" in the for line, but i'm not sure.

Mureinik
  • 297,002
  • 52
  • 306
  • 350

1 Answers1

6

If you only need to display the array backwards, there's no need to swap elements around - just loop from 9 (10-1) down to 0 and print the elements:

public void display()
{
    for (int i = stringarray.length - 1; i >= 0; i--)
    {
        System.out.println (stringarray[i]);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350