我需要製作一個簡單的計算器。我無法輸入任何數量的運算符和操作數,然後在輸入等號按鈕時輸出答案。製作一個簡單的計算器:不能退出循環或給出答案
到目前爲止,如果我只是按一個數字和一個數字它退出但沒有給我一個答案。如果我做了多個操作符和操作數,然後=
它不會退出循環。 例如,它應該是這樣的:
5
+
5
+
5
=
15
這裏是我的代碼,計算器:
public interface Calculator {
public void setOperator(char operator); // eg +-*/=
public void setOperand (double operand); // eg 123.456
public double getResult();
}
SimpleCalculator:
import java.io.*;
public class SimpleCalculator implements Calculator {
char operator;
double operand;
double result;
double answer;
public void setOperator(char operator){
this.operator = operator;
}
public char getOperator(){
return operator;
}
public void setOperand(double operand){
this.operand = operand;
}
public double getOperand(){
return operand;
}
public double getResult(){
if (getOperator() == '+'){
result = (getOperand() + getOperand());
}
if (getOperator() == '-'){
result = (getOperand() - getOperand());
}
if (getOperator() == '*'){
result = (getOperand() * getOperand());
}
if (getOperator() == '/')
{
result = (getOperand()/getOperand());
}
if (getOperator() == '=')
result = answer;
}
return result;
}
public boolean getanswer(String value)
{
boolean isnum = false;
try {
setOperand(Double.parseDouble(value));
operand = (Double.parseDouble(value));
getResult();
isnum = true;
}
catch(Exception e)
{
try {
setOperator(value.charAt(0));
operator = (value.charAt(0));
isnum = false;
}
catch(Exception e2)
{
{
System.out.println("Enter a number");
}
}
return isnum;
}
}
SimpleTest的:基於
import java.io.*;
public class SimpleTest{
static String value;
static double operand;
static char operator;
static boolean isnum;
public static void main(String[] argv){
SimpleCalculator calculator = new SimpleCalculator();
value = UserInput.readString();
while (!(value.equals("=")))
{
isnum = calculator.getanswer(value);
if (!(isnum == true))
{
break;
}
}
System.out.println(calculator.getResult());
}
}
請更具體地說明您遇到的問題。你希望我們只是爲你解決你的計劃嗎? – Blorgbeard 2011-03-22 19:43:41
我很抱歉地說你的代碼設計不好。你自己寫了一切嗎?繼續努力吧,畢竟它是作業。 – Bernard 2011-03-22 19:55:07