【发布时间】:2013-11-12 20:49:55
【问题描述】:
我一直在学习枚举和 switch 语句,我有以下代码
我不想通过代码运行参数,然后编译它以查看结果,我希望用户在终端和 +,x,/,- 中输入数字并在终端中返回结果,我该如何完成这个
public class MathCalculatorTest2_0 {
MathFunctions1_0 mathFunction1;
public MathCalculatorTest2_0 (MathFunctions1_0 mathFunction1) {
this.mathFunction1 = mathFunction1;
}
public void DoMath(double digit1, double digit2) {
double mathResult = 0;
switch (mathFunction1) {
case MULTIPLY:
mathResult = digit1*digit2;
break;
case DIVIDE:
mathResult = digit1/digit2;
break;
case ADD:
mathResult = digit1+digit2;
break;
case SUBTRACT:
mathResult = digit1-digit2;
break;
default:
System.out.println("Incorrect arithmatic character, please insert a correct arithmatic character between the two numbers (x, /, +, -)");
}
System.out.println(mathResult);
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Please correct syntax");
} else {
double firstDigit = Double.parseDouble(args[0]);
String userInput1 = args[1];
double secondDigit = Double.parseDouble(args[2]);
MathCalculatorTest2_0 C;
switch (userInput1) {
case "x":
C = new MathCalculatorTest2_0(MathFunctions1_0.MULTIPLY);
C.DoMath(firstDigit, secondDigit);
break;
case "/":
C = new MathCalculatorTest2_0(MathFunctions1_0.DIVIDE);
C.DoMath(firstDigit, secondDigit);
break;
case "+":
C = new MathCalculatorTest2_0(MathFunctions1_0.ADD);
C.DoMath(firstDigit, secondDigit);
break;
case "-":
C = new MathCalculatorTest2_0(MathFunctions1_0.SUBTRACT);
C.DoMath(firstDigit, secondDigit);
break;
default: System.out.println("Please insert correct arithmatic character.");
}
}
}
}
public enum MathFunctions1_0 {
MULTIPLY, DIVIDE, ADD, SUBTRACT
}
【问题讨论】:
-
首先看看这个:docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html 第二个:不要命名以大写字母开头的变量。第三:给出有意义的名字(这里是类名/实例名)
-
不管怎样,从方法、设计等开始,有很多不好的地方。
-
嗨,谢谢你的 cmets,但是我对 Java 很陌生,我不是计算机科学专业的,我从来没有上过课......所以我不知道如何更好设计任何东西......请不要那么挑剔。另外,这如何帮助我让用户输入 10x10 并得到 100 的结果?
标签: java methods arguments calculator