-2

If my input is 1 2 3 the output is also coming out as 1 2 3, how do I make these numbers to display 3 2 1?

 public static void main(String[] args) {
    // TODO code application logic here
    Scanner s = new Scanner(System.in);

    String text = s.nextLine();


    String[] entries = text.split(" ");
    int[] nums = new int[entries.length];

     for(int i = 0; i < entries.length; i++){
        nums[i] = Integer.parseInt(entries[i]);
    }
     for(int i = 0; i < entries.length; i++){
        System.out.println(nums[i]);
    }
}

}

Flare 2001
  • 11
  • 1

4 Answers4

0

If you want to store numbers in reverse order:

for(int i = 0; i < entries.length; i++)
{
     nums[i] = Integer.parseInt(entries[entries.length-i-1]); 
} 

If you want to just display numbers in reverse order(they'll remain same order in list:

for(int i = entries.length-1; i >= 0; i--)
{
    System.out.println(nums[i]); 
}
Deep Mehta
  • 116
  • 7
0

Try below code:

public static void main(String[] args) 
{
  Scanner s = new Scanner(System.in);
  String text = s.nextLine();
  String[] entries = text.split(" ");
  for(int i = entries.length-1; i >= 0; i--) 
  {
     System.out.print(Integer.parseInt(entries[i])+ " ");
  }
}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Harishma A
  • 61
  • 6
0

If you want Java 8 version, here is the code

Scanner s = new Scanner(System.in);      
String text = s.nextLine(); 
String[] entries = text.split("\\s");

List<Integer> integers = Arrays.stream(entries)
        .map(Integer::valueOf)
        .collect(Collectors.toList());

Collections.reverse(integers);

integers.forEach(integer -> System.out.print(String.format("%d ", integer)));

\\s indicates 'white space' and I suggest you to close Scanner at the end.

the_tech_maddy
  • 575
  • 2
  • 6
  • 21
-1

You could loop through your entries array backwards. This would involve starting int i at the length of entries minus 1 (as that is your last index in your array - ie your last number). It would also require that you keep looping while i >= 0. Lastly, instead of incrementing your i variable, you need to decrement it. This way your counter i will go from the end of your loop to the start of your array (eg: if you enter "1 2 3", i will go from indexes: 2, 1, 0)

See example below:

public static void main(String[] args) {
   // TODO code application logic here
   Scanner s = new Scanner(System.in);

   String text = s.nextLine();


   String[] entries = text.split(" ");
   int[] nums = new int[entries.length];

   for(int i = 0; i < entries.length; i++) {
     nums[i] = Integer.parseInt(entries[i]);
   }
   for(int i = entries.length-1; i >= 0; i--) {
     System.out.println(nums[i]);
   }
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64