Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
In this method i am reading the numbers into an array and then want the array to print numbers in reverse order, however i am doing something wrong here.

What I have tried:

Java
<pre>public void readAndReverse(int n)
    {
        int[] numbers = new int[n];
        Scanner scanner = new Scanner(System.in);
        // Read n integers into an array 
        for (int i = 0; i < n; i++) {
            numbers[i] = scanner.nextInt();
        }
        // Prints n integers in reverse order
        for( int i = 0; i < n; i++) {
            System.out.print(numbers[i] + " ");
            Collections.reverse(numbers[i]);
        }
    }
Posted
Updated 11-Dec-22 8:03am
Comments
0x01AA 11-Dec-22 11:15am    
Think about the below for printing
for( int i = n - 1; i >= 0; i--) ....

To print in reverse order, you need to run the index from N - 1 downward to zero.
Your code runs up from zero to N - 1
 
Share this answer
 
If you really want to reverse the array (as opposed to show its items reversed) then have a look at this page: Reverse An Array In Java - 3 Methods With Examples[^].
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900