我正在创建一个内存计算器。在我的代码中,我有一个当前值方法,当运算符决定加、减、乘等时,需要它返回一个新值...我在弄清楚如何更改当前值字段时遇到了麻烦。当我选择向当前值添加一个数字时,该值保持与之前相同的值 0。
头等舱
import java.util.Scanner;
public class MemoryCalculator {
private double currentValue;
public static int displayMenu() {
Scanner input = new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Add ");
System.out.println("2. Subtract ");
System.out.println("3. Multiply ");
System.out.println("4. Divide ");
System.out.println("5. Clear ");
System.out.println("6. End");
System.out.println("Please choose which math operation to perform, or press 6 to quit.");
int selection = input.nextInt();
return selection;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
System.out.println(prompt);
double operand = input.nextDouble();
return operand;
}
public double getCurrentValue() {
this.currentValue = currentValue;
return currentValue;
}
public void add(double operand2) {
this.currentValue = getCurrentValue() + operand2;
getCurrentValue();
}
public void subtract(double operand2) {
}
public void multiply(double operand2) {
}
public void divide(double operand2) {
}
public void clear() {
}
}
二级驾驶员等级
public class MemoryCalculatorDriver {
public static void main(String[] args) {
double operand2 = 0;
MemoryCalculator CalcObj = new MemoryCalculator();
System.out.println(CalcObj.getCurrentValue());
int selection = CalcObj.displayMenu();
if(selection == 1) {
System.out.println(CalcObj.getOperand("What would you like the second number to be"));
CalcObj.add(operand2);
System.out.println(CalcObj.getCurrentValue());
}else if (selection == 2) {
System.out.println(CalcObj.getOperand("What would you like the second number to be"));
CalcObj.subtract(operand2);
System.out.println(CalcObj.getCurrentValue());
}else if (selection == 3) {
System.out.println(CalcObj.getOperand("What would you like the second number to be"));
CalcObj.multiply(operand2);
System.out.println(CalcObj.getCurrentValue());
}else if (selection == 4) {
System.out.println(CalcObj.getOperand("What would you like the second number to be"));
CalcObj.divide(operand2);
System.out.println(CalcObj.getCurrentValue());
}else if (selection == 5) {
CalcObj.clear();
System.out.println(CalcObj.getCurrentValue());
}else if (selection == 6) {
System.out.println("Goodbye");
}
}
}
我能够从用户那里获取选择输入,并且我可以从用户那里获取第一个数字。当我选择选项1“添加”时,用户可以输入数字,但是该数字没有添加到当前值。
最佳答案
您通过此方法返回值public static double getOperand(String Prompt)
但是您在哪里使用了返回值?
一定是这样的:
if(selection == 1) {
operand2 = CalcObj.getOperand("What would you like the second number to be"));
CalcObj.add(operand2);
System.out.println(CalcObj.getCurrentValue());
// your code like this...
}
关于java - 如何添加计算器的当前值方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60243078/