0

I just started coding three or four weeks ago. Today I began a calculator project, but quickly ran into an error. Here is the code:

import java.util.Scanner;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
            Scanner scanner = new Scanner(System.in);
            System.out.println("This is a basic calculator. +, -, *, or /?");
            String function = scanner.next();
            scanner.close();
            switch(function) {
            case "+":
                add();
            break;
            case "-":
                
            break;
            case "*":
                
            break;
            case "/":
                
            break;
            }
    }
    static void add() {
        Scanner scanner = new Scanner(System.in);
            int adding = scanner.nextInt();
    }
}

My error is:

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 Main.add(Main.java:28)
at Main.main(Main.java:13)
khelwood
  • 52,115
  • 13
  • 74
  • 94
  • 3
    Closing a scanner also closes the underlying stream. Once you've closed System.in, you can't read from it any more. – azurefrog Sep 08 '21 at 21:36

0 Answers0