javajava.util.scannernosuchelementexception

NoSuchElementException in nextInt() no matter what I do to the code


public class MinimumElement {

public void readIntegers(int userCount) {
    int count = userCount;
    int intArray[] = new int[count];
    Scanner scan = new Scanner(System.in);

    for (int i = 0; i <= count - 1; i++) {
        int number;
        System.out.println("Please input number ");
        number = scan.nextInt();
        intArray[i] = number;
    }
    scan.close();
}

public static void main(String[] Args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter the number of elements required for array");
    int userInput = scan.nextInt();
    scan.nextLine();
    scan.close();
    MinimumElement min = new MinimumElement();
    min.readIntegers(userInput);

}

}

Have tried hasNextInt and hasNextLine with if conditions as well. They are always returning result value as false.


Solution

  • Alright, I believe I might've found a solution to your problem. The issue lies within the way you attempt to read from System.in: you allocate two instances of Scanner tied to the same System.in input stream.

    int intArray[] = new int[count];
    Scanner scan = new Scanner(System.in);
    

    And over there:

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter the number of elements required for array");
    

    This is going to cause problems. Therefore, create a global instance of Scanner like shown in the example below instead.

    public class MinimumElement {
    
        private static Scanner SCANNER;
    
        public static void main(String[] args) {
            SCANNER = new Scanner(System.in);
    
            System.out.println("Please enter the number of elements required for array");
            try {
                int userInput = SCANNER.nextInt();
                SCANNER.nextLine();
                MinimumElement min = new MinimumElement();
                min.readIntegers(userInput);
            } finally {
                SCANNER.close();
            }
        }
    
        public void readIntegers(int userCount) {
            int[] intArray = new int[userCount];
            for (int i = 0; i <= userCount - 1; i++) {
                int number;
                System.out.println("Please input number ");
                number = SCANNER.nextInt();
                intArray[i] = number;
            }
        }
    }
    

    Note that you must take care not to interact with the Scanner after invoking its close() method, as that will result in erroneous behaviour as well.