好的,这是我开始使用的计算器的代码。
import java.awt.*;
import java.applet.*;
public class Calculator extends Applet
{
private Label calculatorL; //Sets the label
private boolean firstDigit = true; //Sets Boolean firstDigit to be true
private float savedValue = 0.0f;//Sets saved value to 0
private String operator = "="; //Sets Default operator
public void init ()
{
setLayout (new BorderLayout()); //Sets the layout
add ("North", calculatorL = new Label ("0", Label.RIGHT));
Panel calculatorPanel = new Panel(); //Adding a panel for the buttons
calculatorPanel.setLayout (new GridLayout (4, 4)); //Adding a 4 * 4 grid for the layout of the buttons
calculatorPanel.setBackground(Color.CYAN);
calculatorPanel.setForeground(Color.BLUE);
addButtons (calculatorPanel, "123-");
addButtons (calculatorPanel, "456*");
addButtons (calculatorPanel, "789/");
addButtons (calculatorPanel, ".0=+");
add("Center", calculatorPanel);
}
public boolean action (Event event, Object inputobject)
{
if (event.target instanceof Button)
{
String inputstring = (String)inputobject;
if ("0123456789.".indexOf (inputstring) != -1)
{
if (firstDigit)
{
firstDigit = false;
calculatorL.setText (inputstring);
}
else
{
calculatorL.setText(calculatorL.getText() + inputstring);
}
}
else
{
if(!firstDigit)
{
solve(calculatorL.getText());
firstDigit = true;
}
operator = inputstring;
}
return true;
}
return false;
}
public void solve (String valueToBeComputed)
{
float sValue = new Float (valueToBeComputed).floatValue();
char c = operator.charAt (0);
switch (c)
{
case '=': savedValue = sValue;
break;
case '+': savedValue += sValue;
break;
case '-': savedValue -= sValue;
break;
case '*': savedValue *= sValue;
break;
case '/': savedValue /= sValue;
break;
}
calculatorL.setText (Float.toString(savedValue));
}
public void addButtons (Panel panel, String labels)
{
int count = labels.length();
for (int i = 0; i<count; i ++)
{
panel.add (new Button (labels.substring(i,i+1)));
}
}
}
我尝试做的是将我的求解器代码转移到自己独立的类中。
这是我到目前为止所拥有的
import java.awt.*;
public class Solver
{
private String operator = "="; //Sets Default operator
private float savedValue = 0.0f;//Sets saved value to 0
public void solve (String valueToBeComputed)
{
float sValue = new Float (valueToBeComputed).floatValue();
char c = operator.charAt (0);
switch (c)
{
case '=': savedValue = sValue;
break;
case '+': savedValue += sValue;
break;
case '-': savedValue -= sValue;
break;
case '*': savedValue *= sValue;
break;
case '/': savedValue /= sValue;
break;
}
calculatorL.setText (Float.toString(savedValue));
}
}
使用/创建我自己的自定义类真的很新。可以使用一些帮助转移和设置解算器类。
答案 0 :(得分:1)
移动代码有时被称为重构 ...
您可以在新课程中设置solve
方法 static ,然后将其称为
Solver.solve(calculatorL.getText());
使用
实例化Solve
对象
Solve mySolve = new Solve();
然后用:
调用该对象的方法mySolve.solve(calculatorL.getText());
最后,要返回计算出的值,您应该将方法类型从void
更改为String
或float
,然后将其传递给calculatorL.setText()
。