Java 为我的计算器小程序创建类
这是我开始使用的计算器的代码Java 为我的计算器小程序创建类,java,class,applet,refactoring,Java,Class,Applet,Refactoring,这是我开始使用的计算器的代码 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 savedValu
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)));
}
}
}
对于使用/创建我自己的自定义类来说,这是一个全新的概念。可能需要一些帮助来转移和设置解算器类 移动代码有时被称为重构 您可以在新类中使
solve
方法保持静态,然后像这样调用它
Solver.solve(calculatorL.getText());
或者用
Solve mySolve = new Solve();
然后使用以下命令调用该对象的方法:
mySolve.solve(calculatorL.getText());
最后,要返回计算值,您应该将方法类型从
void
更改为String
或float
,然后将其传递给calculatorL.setText()
您的问题是什么?我正在寻找创建自定义类的帮助。我不确定它们是如何工作的。只是想找人帮我把解题代码转移到一个单独的类中。1)为什么要使用AWT?有关放弃AWT组件而支持Swing的许多好理由,请参阅。2) 为什么要编写小程序?如果是老师指定的,请参考。。。。3) 见和。4) 另见此。它使用ScriptEngine
计算文本字段中的表达式。感谢我现在开始了解自定义类是如何工作的。这就是我现在在解算器类中的内容,也是我现在在主程序中的内容。
mySolve.solve(calculatorL.getText());