我是 java 编程的新手,我刚刚创建了一个计算器程序,它似乎工作正常,但其他程序员似乎在他们的计算器程序中使用“解析很多”。只是想问一下我是否采取了错误的方法,并且将来使用这种逻辑可能会遇到问题。谢谢。
class Refresh {
private final String a;
private final String b;
private final String c;
private final String d;
private double x, y;
public Refresh() {
a = "Enter the first number: ";
b = "Enter the function; ";
c = "Enter the second number: ";
d = "The result is: ";
}
public void types() {
Scanner typ = new Scanner(System.in);
try {
System.out.println(a);
x = typ.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Please use only numbers!");
System.exit(1);
}
System.out.println(b);
String func = typ.next();
try {
System.out.println(c);
y = typ.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Please use only numbers!");
System.exit(1);
}
switch (func) {
case "+":
System.out.println(d + (x + y));
break;
case "-":
System.out.println(d + (x - y));
break;
case "/":
if (y == 0) {
System.out.println("Cannot divide by zero!");
} else {
System.out.println(d + (x / y));
}
break;
case "*":
System.out.println(d + (x * y));
break;
default:
System.out.println(func + " is not valid function");
}
}
public static void main(String[] args) {
Refresh fin = new Refresh();
fin.types();
}
}