Search code examples
javanosuchelementexception

`Enter Activity Number: Exception in thread "main" java.util.NoSuchElementException


Newbie here, The program works, I can call the class but I don't know what is this. I tried to search but it's not the same problem I encounter

import java.util.*;

public class mid_term {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean ok = true;
        Act1 act_1 = new Act1();

        do {
            System.out.println("Midterm Project...Press [0] to exit.\n\n\n");
            System.out.println("[1] Activity 1 (Grade Calculator).");


            System.out.print("Enter Activity Number: ");
            int choice = input.nextInt();

            switch (choice) {
            case 1:
                act_1.main(args);
                break;
            default:
                break;
            }

        } while (ok);
    }

}
import java.util.*;

public class Act1 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter Prelim Grade: ");
        double prelim = input.nextDouble();

        System.out.print("Enter Midterm Grade: ");
        double midterm = input.nextDouble();

        System.out.print("Enter Final Grade: ");
        double finals = input.nextDouble();

        
        double result = ((prelim*.30) +(midterm*.30)+ (finals*.40));
        System.out.println("Final Ratings: " + result);

        input.close();

    }
}

Enter Activity Number: Exception in thread "main" java.util.NoSuchElementException

How can I solve this?


Enter Activity Number: 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 mid_term.main(mid_term.java:23)

Solution

  • In the class Act1 you call

     input.close();
    

    it closes your System.in stream in the end of the 1st iteration.

    In the class mid_term you have an infinite loop, if you want your program work without NoSuchElementException, you should keep your stream open. Delete the

    input.close();