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.