需求分析與設計思路:
建立一個簡易電腦,首先要建立一個窗體,并且要有簡單的輸入資料的架構。
向窗體中添加三個TextField 便于使用者輸入要計算的數,添加choice下拉選擇框,
便于使用者輸入+-* /符号, lable用來顯示=,Button按鈕用來顯示"計算"以便用
戶算出最終結果,最後利 用if語句判斷出使用者要進行哪種運算。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLykjN3kTM3AzMtAzMyMDN4MDMyQDMwETNxAjMtAzM2ETM48CXwETNxAjMvwFMzYTMxgzLcd2bsJ2Lc12bj5ycn9Gbi52YuUTMwIzcldWYtl2Lc9CX6MHc0RHaiojIsJye.png)
代碼實作:
package pp;
import java.awt.Button;
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test {
public static void main(String[] args) {
Frame frame = new Frame("簡易電腦");
frame.setSize(300,150);
frame.addWindowListener(new Listener());
final TextField tf1 = new TextField(8);
final Choice choice = new Choice();
choice.addItem("+");
choice.addItem("-");
choice.addItem("*");
choice.addItem("/");
final TextField tf2 = new TextField(8);
Label label = new Label("=");
final TextField tf3 = new TextField(8);
Button button = new Button("計算");
frame.add(tf1);
frame.add(choice);
frame.add(tf2);
frame.add(label);
frame.add(tf3);
frame.add(button);
frame.setLayout(new FlowLayout());
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String s1 = tf1.getText();
String s2 = tf2.getText();
String ch = choice.getSelectedItem();
double d1 = Double.parseDouble(s1);
Double d2 = Double.parseDouble(s2);
double d = 0;
if (ch.equals("+"))
{
d=d1+d2;
}
else if(ch.equals("-"))
{
d=d1-d2;
}
else if (ch.equals("*"))
d=d1*d2;
}
else
{
d=d1/d2;
}
tf3.setText(d + " ");
}
});
frame .setVisible(true);
}
運作測試:
}
本次代碼測試大概用了兩個小時。
總結:首先要有清晰的思路,知道第一步是建立一個窗體,然後完整整個窗體的内容,分析使用者需求,按使用者要求實作代碼,最後測試。