1

I am supposed to be writing a program to reverse the numbers in an array recursively. I don't really know much code at this point. This is what I have so far.

This is the reverse method itself:

  public static void reverse(int[] array, int i, int j)
  {
    if (i < j)
    {
      int temp = array[i];
      array[i] = array[j];
      array[j] = temp;
      reverse(array, ++i, --j);

I am not sure if this is even right. I then have the main method.

  public static void main(String[] args)
  {
   Scanner input = new Scanner(System.in);
   System.out.println("Enter size of the array");
   int n = input.nextInt();
   int[] array = new int[n];

   for (int i =0; i <array.length; i++)
   {
     System.out.println("Enter number to be inputed into array.");
     array[i] = input.nextInt();

   }
    System.out.println(array);
  }

It is not printing out right and prints numbers and letter in text where I think it should be the array.

6
  • Your code is incomplete, could post the whole reverse method? Commented Nov 5, 2013 at 23:18
  • I think it's just missing a couple closing braces. Commented Nov 5, 2013 at 23:20
  • yeap likely but better make sure. Commented Nov 5, 2013 at 23:21
  • 1
    Note: The main method isn't actually calling reverse. Commented Nov 5, 2013 at 23:22
  • That is my code. It is just missing braces like ajb said. It still isn't working though. I can't call my method correctly. Commented Nov 5, 2013 at 23:35

1 Answer 1

2

Change System.out.println(array); to this:

System.out.println(Arrays.toString(array));

Then you can see whether or not your method is properly reversing. Currently, you're not printing the contents of the array, just the memory address where your array resides.

Sign up to request clarification or add additional context in comments.

3 Comments

What is a String? Excuse my probably stupid question.
String is a data type which essentially represents an array of chars. This probably isn't technically write, but a String is a data type that holds words, phrases, etc., in much the same way int is a data type which holds integers.
A ummutable sequence of characters.

Your Answer

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