0

I know this question has been asked in other languages including Java itself.

I just want to clarify that I know how to reverse an array but I would rather appreciate help if any for this particular solution of mine. So please don't mark it as a duplicate.

import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
    /*
         Code for User input
    */

    /* The problem was with the Swapping Code below */
    for(int i=0; i<=n/2; i++)
        swap(i,n-i-1,a);

  /* Output Code. */

    }
/*Swap function*/
public static void swap(int x, int y, int[] arr){
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

}

I have changed my solution according to the links provided in the comments .I am getting alright in some of the test cases but in some, the code fails.I think I have done it correctly.So any help will be appreciated.Thanks

5
  • 1
    You're just swapping two int variables which does nothing. What you need is swap the contents of the array. Something like temp = a[x]; a[x] = a[y]; a[y] = temp; Commented Oct 24, 2016 at 3:35
  • 5
    Sorry, but I think this should be marked as a duplicate of stackoverflow.com/questions/2393906/…, because that solves your problem perfectly. Commented Oct 24, 2016 at 3:36
  • 1
    @ajb specifically the first snippet in polygenelubricants's answer there. Commented Oct 24, 2016 at 3:38
  • I changed the code according to the snippet.But in some cases my code is failing.Can anyone just tell me what I am doing wrong now? Commented Oct 24, 2016 at 3:54
  • 1
    To form better question and make it an minimal reproducible example and easier to answer, replace all the input part with String a[] = new String[]{/*an array which fails*/}; Commented Oct 24, 2016 at 4:17

1 Answer 1

1

Thanks to conscells,ajb and Amadan to lead me to the correct place for getting a solution to this problem.

Here is the correct solution for reversing the array in Java.I know there are solutions provided for it already here but just thought to make this question somewhat useful for future users.Thanks.

import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int a[] = new int[n];
    for(int i=0; i < n; i++)
        a[i] = scan.nextInt();
    for(int i=0; i < n/2; i++)
        swap(i,n-i-1,a);
    for(int i = 0; i < n; i++)
        System.out.println(a[i]);
    }

public static void swap(int x, int y, int[] arr) {
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.