简体   繁体   中英

JAVA: NoSuchElementException while function executing second time

I'm working on simple Calculator app on Java. When user enter 0(which returns info no math operator), i want to restart my function. But when I do it throws NoSuchElementException when debug pointer comes to int operationInput = sc.nextInt(); Here is the my whole code block. I tried try catch but it stucks. Maybe it cannot re-identify a variable because it doesn't quit of that code block.

static Object mathOperators() {
        
        Scanner sc = new Scanner(System.in);
        System.out.print("Please enter a number for choosing operation(if you don't know what operation equals to which number click 0): ");
        int operationInput = sc.nextInt();
        sc.close();
        
        switch (operationInput) {
        case 0:
            System.out.println("1: Addition - 2: Subtraction - 3: Multiplication \n"
                    + "4: Division - 5: Modulus");
            return mathOperators();
        case 1:
            System.out.println(additionCalc());
            break;
        case 2:
            System.out.println(substractionCalc());
            break;
        case 3:
            System.out.println(multiplyCalc());
            break;
        case 4:
            System.out.println(divisionCalc());
            break;
        case 5:
            System.out.println(modulusCalc());
            break;
        default:
            System.out.println("Please enter a valid number");
            break;
        }
        
        return 0;
    }

You can use only one Scanner(System.in) in your app. You must close the scanner before calling "break" in your switch cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM