我正在构建一个简单的计算器,要求用户选择该功能。
菜单显示如下,用户可以选择1-5作为选项以及A,S,M和D,因为它具有受尊重的功能:
计算器将要求用户选择由空格分隔的2个浮点数并计算它等等。它将拒绝任何不是上述的输入。
反正。我得到了大部分计算器编码。但是,现在,我只对它进行编码,以允许用户选择1-5而不是1-5以及字母。我确实有一个单独的代码,允许用户选择1-5或A,S,M,D,但我不知道如何调用该方法将其输入到计算器的主代码中。我应该以什么格式编写呼叫,以便使用第二段代码而不是第一段代码,这样用户不仅可以输入1-5而且可以输入1-5和A,S,M或D.谢谢
下面是我需要调用AskCalcChoice1的部分,但是我收到错误AskCalcChoice1无法解决:
while ((inputOperation = myAskCalcChoice1.userInput()) != 5) //Need to call for the method below but how?{
calculatorCommands.pickNewSymbol("\n");
calculatorCommands.putDownSymbol();
以下是askCalcChoice1的切换方法。如何将此方法调用到主计算器代码中?
import java.util.Scanner;
公共课askCalcChoiceSwitch {
Scanner readInput = new Scanner(System.in);
public float showResults(int choice, float [] f){
float result = 0.00f;
char input = readInput.nextLine().charAt(0);
switch (input) {
case '1': result = f[0]+f[1]; break; //if user input choice 1, function will break after this
case 'A': result = f[0]+f[1]; break; //if user input choice A, function will break after this
case '2': result = f[0]-f[1]; break; //if user input choice 2, function will break after this
case 'S': result = f[0]-f[1]; break; //if user input choice S, function will break after this
case '3': result = f[0]*f[1]; break; //if user input choice 3, function will break after this
case 'M': result = f[0]*f[1]; break; //if user input choice M, function will break after this
case '4': result = f[0]/f[1]; break; //if user input choice 4, function will break after this
case 'D': result = f[0]/f[1]; break; //if user input choice D, function will break after this
default: System.out.println("Calculator cannot comprehend" + choice); break;
}
return result;
}
}
答案 0 :(得分:0)
考虑使用switch语句。
编辑:我添加了一个CalOperation接口和具体类型来封装数学运算并简化代码。
private CalcOperation calcChoice () {
while (true) {
String input = readInput.nextLine();
switch (input) {
case "1": //intentional fall through
case "A":
return new AddOperation();
case "2": //intentional fall through
case "S":
return new SubtractOperation();
case "3": //intentional fall through
case "M":
return new MultiplyOperation();
case "4": //intentional fall through
case "D":
return new DivideOperation();
default:
System.out.println("You have entered an invalid choice. Try again.");
break;
}
}
}
public interface CalcOperation {
public double calculate(double d1, double d2);
}
public class AddOperation implements CalcOperation {
@Override
public double calculate (double d1, double d2) {
return d1 + d2;
}
}
//create implementations for SubtractOperation, MultiplyOperation, and DivideOperation