1

Im working on an assignment for a beginners Java course, and Im having a problem with printing out an array the way that its asking for. The problem is as follows:

"Write a program that asks the user "How many numbers do you want to enter?" With that value, create an array that is big enough to hold that amount of numbers (integers). Now ask the user to enter each number and store these numbers into the array. When all the numbers have been entered, display the numbers in reverse order from the order in which they were entered."

I have everything except the last part, displaying the numbers in reverse order.

Any help on this would be appreciated.

Heres What I have so far:

import java.util.Scanner;

public class ArraysNickGoldberg
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        System.out.print("How many numbers do you want to enter?");

        final int NUMBER_OF_ELEMENTS = input.nextInt();

        int[] myList = new int[NUMBER_OF_ELEMENTS];

        for( int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
            System.out.println("Enter a new number: ");
            myList[i] = input.nextInt();
        }

        for( int i = 0; i < NUMBER_OF_ELEMENTS; i++){
            System.out.print(myList[i] + " ");
        }

    }
}

2 Answers 2

2

try

   for( int i = NUMBER_OF_ELEMENTS - 1; i >= 0; i--){
            System.out.print(myList[i] + " ");
   }

You may also want to look at Java Array Sort

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

Comments

0

to print it in reverse order, you just need to simply reverse your for loop :)

so instead of

for(int i=0; i< NUMBER_OF_ELEMENTS; i++){
}

use this instead:

for(int i=NUMBER_OF_ELEMENTS - 1; i >= 0; i--){ //remember to minus 1 or else you'll get index of out of bound
}

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.