Reversing an array using java

ShadowHunter :

I am having trouble trying to reverse arrays and it keeps on printing out this message can you help figure out what I am doing wrong.

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at LabProgram.main(LabProgram.java:13)

import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int[] userList = new int[20];   
      int numElements;                
      int i; 

      numElements = scnr.nextInt();   

      for (i = 0; i < userList.length; ++i) {
         userList[i] = scnr.nextInt();

      }
      for (i = 0; i < userList.length/2; ++i) {
         int temp = userList[i];
         userList[i] = userList[userList.length -i -1];
         userList[userList.length -i -1] = temp;
      }
      for (i = 0; i < userList.length; ++i) {
         System.out.print(userList[i] + " ");
      }          
   }
}

example if the input is:

5 2 4 6 8 10

then the output is:

10 8 6 4 2
Arvind Kumar Avinash :

Do it as follows:

import java.util.Scanner;

public class LabProgram {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        System.out.print("Enter the number of intgers: ");
        int numElements = scnr.nextInt();
        int[] userList = new int[numElements];
        int i;
        System.out.println("Enter " + numElements + " integers");
        for (i = 0; i < userList.length; ++i) {
            userList[i] = scnr.nextInt();
        }
        for (i = 0; i < userList.length / 2; ++i) {
            int temp = userList[i];
            userList[i] = userList[userList.length - i - 1];
            userList[userList.length - i - 1] = temp;
        }
        for (i = 0; i < userList.length; ++i) {
            System.out.print(userList[i] + " ");
        }
    }
}

A sample run:

Enter the number of intgers: 6
Enter 6 integers
1
2
3
4
5
6
6 5 4 3 2 1 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345050&siteId=1