我是一名java學生,我正致力於讓我的代碼更加面向對象。我可以很容易地在主代碼計算器,但我真的很努力用方法來實現它。以下代碼將始終返回0 ...但目標是創建一個允許用戶在一行中輸入運算符和數字的程序(示例+5),代碼應該輸出前一個值,新值以及允許重置。我相信,我真的很接近解決這一併且只需要一個點在正確的方向..爲什麼calculator.getValue()總是0?
輸出
Enter an operator and a number:
+5
0.0
計算器類
import java.util.Scanner;
public class Calculator {
private final int RESET = 0;
private double number = 0;
private double result = 0; // I believe this is the issue but how can I resolve it?
private char operator;
private static Scanner keyboard = new Scanner(System.in);
public Calculator(double number)
{
this.number = number;
}
// this method invokes the whatOperator() to create a new result
// the edited method still returns 0
public double aResult(Calculator other)
{
other.whatOperator();
this.result = other.result;
return result;
}
// I created this method in hopes that it would do most of the work..when I invoke it and enter my operator and number it does not seem to function correctly
public void whatOperator()
{
String operator = null;
operator = enterNumber();
double theNumber = Double.parseDouble(operator);
char theOperator =operator.charAt(0);
operator = null;
operator += theOperator;
// switch method to find the operator
switch(operator){
case "*":
result = getNumber() * theNumber;
break;
case "/":
result = getNumber()/theNumber;
break;
case "+":
result = getNumber() + theNumber;
break;
case "-":
result = getNumber() - theNumber;
break;
case "R":
result = RESET;
break;
}
}
// methods for operation...I was hoping to not use these
public double add(double secondNumber)
{
result = number + secondNumber;
return result;
}
public double divide(double secondNumber)
{
result = number/secondNumber;
return result;
}
public double multiply(double secondNumber)
{
result = number * secondNumber;
return result;
}
public void subtract(double secondNumber)
{
result = number - secondNumber;
}
public double getNumber()
{
return number;
}
// method for getting input
public static String enterNumber()
{
System.out.println("Enter an operator and a number:");
String toString = keyboard.nextLine();
return toString;
}
public static void main (String[] args) {
// the calculator is initialized at 0
Calculator a = new Calculator(0);
// now I create a second calculator with the result from the aResult()
Calculator b = new Calculator(a.aResult(a));
// why is b.getNumber() = 0 at this point?
String theString = String.valueOf(b.getNumber());
// prints 0 every time
System.out.println(theString);
}
}
在您發佈的代碼中沒有'getNumber()'方法。 – shmosel
in aResult'this.result = result' does not nothing,it should read'this.result = other.aResult()' – Turo
在一般說明中,爲每個計算步驟創建一個新的'Calculator'非常奇怪。應該只有一個實例。 – shmosel