Question

import java.util.Scanner;

public class ReverseOrder
{

    char input;

   public static void main (String[] args)
   {


       Scanner reader = new Scanner (System.in);

       char [] ch = new char[5];


      System.out.println ("The size of the array: " + ch.length);

      for (char index = 0; index < ch.length; index++)
      {
         System.out.print ("Enter a char " + (index+1) + ": ");
         ch[index] = reader.next().charAt(0);
      }

      System.out.println ("The numbers in reverse order:");

      for (char index = (char) (ch.length-1); index >= 0; index--)
         System.out.print (ch[index] + "  ");
       }

}
Was it helpful?

Solution

You are suffering from a char overflow.

The main problem is with your loops...

for (char index = 0; index < ch.length; index++)

and

for (char index = (char) (ch.length-1); index >= 0; index--)

Which are using char. Try changing them to use int instead, for example...

for (int index = 0; index < ch.length; index++)

and

for (int index = (ch.length-1); index >= 0; index--)

OTHER TIPS

The problem is that you are using char for your for loops

Change to

for (int index = 0; index < ch.length; index++)

and

for (int index = ch.length - 1; index >= 0; index--)

When printing the char array.

You should make the following change:

Change

for (char index = (char) (ch.length-1); index >= 0; index--)

to

 for (int index =  ch.length-1; index >= 0; index--)

An example prints is as follows:

The size of the array: 5
Enter a char 1: 1
Enter a char 2: 2
Enter a char 3: 3
Enter a char 4: 4
Enter a char 5: 5
The numbers in reverse order:
5  4  3  2  1  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top