Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Reversed Arrays in Java (help)

A program need to ask a user for input. User needs to enter some numbers and program should display the reversed version. For e.g User enters 1,2,3,4,5 and the end result is 5,4,3,2,1.. I tried this code, but it doesn't show desired results.Does any1 know how to solve this, or at least to wants to help me to figure this out? Kind regards.

public class Practice1 {
    public static void main (String[] args) {
        Practice1 reversedArray = new Practice1();
        reversedArray.generateData();
    }

    public void generateData(){
        Scanner n = new Scanner(System.in);
        System.out.println("Enter numbers");
        int x= n.nextInt();
        int array[] = new int[x];
        for(int i = 0; i<array.length; i++){
            x = new Random().nextInt(10)-1;
            array[i] = x;      
        }

        printArray(array);
        reverseArray(array);       
    }

    public void printArray(int array[]){
        for(int i =0; i <array.length; i++){
        System.out.println(array[i] +" ");
    }
        System.out.println("\n");
    }

    public void reverseArray(int array[]){

        int temp;
        for(int i = 0; i < array.length; i++){
            for(int j = 0; j<array.length - i-1; j++){
                temp= array[j];
                array[j] = array[j+1];
                array[j+1] = temp;               
            }
        }
        printArray(array);
    }   
}

1 Answer

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Milan;

Have you looked at the Commons Language library which has a built in method for doing this?

ArrayUtils.reverse(int[] array)

Just a thought. If you have to build it yourself, there are a multitude of sources online that show working code. Here is one such spot.

Happy coding,
Ken

Thank you for your answer. This is my first time with Java, and it is little confusing.