0

I'm wondering how to display the contents of an array from the last user input to the first user input. For example, if the user input 67 12, I would want to display 12 67, or 56 12 45 23, I would want 23 45 12 56. Unfortunately googling this and searching here only gets me results on descending order which I already have written in another part of my code. Thank you for any help, this is my current code:

import java.util.*;
class Array{
  public static void main(String args[]){
      int[] a=new int[2];
      int[] b=new int[a.length];
      Integer[]c = new Integer[a.length];

      Scanner input=new Scanner(System.in);

      System.out.println("Please enter two numbers:");
      for(int j=0;j<2;j++){
          a[j]=input.nextInt();
       }

      System.arraycopy(a,0, b, 0, a.length);

      for(int i = 0; i < a.length; i++){
          c[i] = new Integer(a[i]);
      }


      Arrays.sort(a);

      int i;

      System.out.println("Last to First:");

      //Display contents of array 'a' from last user input to first user input.

      System.out.println("Ascending order:");

      for(i=0; i < a.length; i++) {
        System.out.println(a[i]);
      }

      Arrays.sort(c, Collections.reverseOrder());

      System.out.println("Descending order:");

      for(i=0; i < c.length; i++) {
        System.out.println(c[i]);
      }

  }

}

2
  • For the printing loop, put[ i=c.length-1;i>=0;i--] Commented Sep 8, 2016 at 4:32
  • you just want to print the Array in reverse order right? why dont you loop in backward manner? Commented Sep 8, 2016 at 4:34

1 Answer 1

1
if your array is like this : 
arr[0] = 56
arr[1] = 12
arr[2] = 45
arr[3] = 23

get the length and count your loop decremented

for(int i = arr.length - 1; i >= 0 ; i--) {
     System.out.println(arr[i]);
   }
Sign up to request clarification or add additional context in comments.

4 Comments

It should be arr.length-1. Because array positions start from 0.
Ahh my bad.. i forgot.. :)
This worked perfectly using the -1. Thank you both very much for your help!
@lbreedlove If you have got an answer to the question, then please mark the answer as the correct one.

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.