//❗it does not exit loop when there is an error
import java.util.InputMismatchException;
import java.util.Scanner;
public class Coolin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 🚩 what if the user inputs a string accidentally?
boolean isValid = false;
int firstNum = 0;
while(true) {
try {
System.out.print("Enter First Number : ");
firstNum = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Must be an integer");
sc.next();
}
//❗it does not exit loop when there is an error
}
int secondNum = 0;
try {
System.out.print("Enter Second Number : ");
secondNum = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Must be an integer");
}
System.out.println("""
Welcome to Calculator 🧮
Please choose the method in which you want to solve
[1️⃣] ➕ Addition ➕
[2️⃣] ➖ Subtraction ➖
[3️⃣] ➗ Division ➗
[4️⃣] ✖️ Multiplication ✖️
""");
int choose = 0;
try {
System.out.print("Enter Method : ");
choose = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Must be an integer");
}
switch (choose) {
case 1 -> System.out.println(firstNum + " + " + secondNum + " = " + (firstNum + secondNum));
case 2 -> System.out.println(firstNum + " - " + secondNum + " = " + (firstNum + secondNum));
case 3 -> System.out.println(firstNum + " / " + secondNum + " = " + (firstNum + secondNum));
case 4 -> System.out.println(firstNum + " * " + secondNum + " = " + (firstNum + secondNum));
default -> System.out.println("Invalid");
}
}
}
-删除未使用的布尔值 -您已经使用 sc.next() 修复了循环问题; - 你没有在第二个数字中添加 try-catch -我把你的评论改为绿色🟢