2

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
ShadowHunter
  • 41
  • 1
  • 5

2 Answers2

0

Here is example check it


public class ReverseArray { 

    /* function that reverses array and stores it  
       in another array*/
    static void reverse(int a[], int n) 
    { 
        int[] b = new int[n]; 
        int j = n; 
        for (int i = 0; i < n; i++) { 
            b[j - 1] = a[i]; 
            j = j - 1; 
        } 

        /*printing the reversed array*/
        System.out.println("Reversed array is: \n"); 
        for (int k = 0; k < n; k++) { 
            System.out.println(b[k]); 
        } 
    } 

    public static void main(String[] args) 
    { 
        int [] arr = {10, 20, 30, 40, 50}; 
        reverse(arr, arr.length); 
    } 
} 
Krishna Sony
  • 957
  • 6
  • 21
0

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 
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72