????
一、計算器的實作邏輯
- 獲得點擊的按鈕的字串名稱,
- 判斷:若點擊數字按鈕" 0-9 " 和 " . " ,將其顯示在內容框中, 若點擊運算運算子時不顯示在內容框中,并且記錄之前所輸入的數字字串,當點擊 " = " 時,得到此時文本框中顯示的字串,將第一次的字符字串和此時的字串轉換為數值型,運算,回傳結果,
二、代碼如下
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Practice extends JFrame implements ActionListener{
//創建二維陣列,作為按鈕名
String name[][]= {{"1","2","3","+"},
{"4","5","6","-"},
{"7","8","9","*"},
{"0",".","=","/"}};
//創建按鈕陣列
JButton button[][] = new JButton[4][4];
//創建面板物件陣列
private JPanel temp[] = new JPanel[4];
//創建單行文本框,作為顯示
JTextField text = new JTextField();
//第一次的輸入陣列字串,運算子,第二次的陣列字串
private String firstInput = null;
private String operator = null;
private Double result;
public Practice() {//構造方法
super("Calculator");
this.setBounds(300,400,400,400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//設定為網格布局,5行,1列,每一行添加一個面板
this.getContentPane().setLayout(new GridLayout(5,1));
this.add(text);
this.text.setHorizontalAlignment(JTextField.RIGHT);//在右邊顯示輸入的字符
text.setEditable(false);//設定為不可編輯
for(int i = 0;i<4;i++) {//實體化panel物件,添加到頂層容器中
temp[i] = new JPanel(new GridLayout(1,4));
this.add(temp[i]);
}
//將按鈕添加到指定位置,添加事件監聽器,添加到面板中
for(int i = 0;i < 4;i++) {
for(int j = 0;j<4;j++) {
button[i][j] = new JButton(name[i][j]);
button[i][j].addActionListener(this);
temp[i].add(button[i][j]);
}
}
//添加面板
for(int i = 0;i<4;i++) {
this.add(temp[i]);
}
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//獲得所點擊按鈕的字串
if(".0123456789".indexOf(str)!=-1) {//回傳目標字串在字串中的下標,如果沒有,則回傳-1
text.setText(text.getText()+str);
}else if(str.matches("[\\+\\-*/]{1}")){
operator = str;//記錄下運算子
firstInput = text.getText();//將第一次輸入的值記錄
text.setText("");//將文本框清空
}else if(str.equals("=")) {
Double num1 = Double.valueOf(firstInput);//String 型別轉換為Double 型
Double num2 = Double.valueOf(text.getText());//點擊運算子之后,再次點擊的數字
switch(operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1*num2;
break;
case "/":
if(num2!=0) {
result = num1/num2;
}
break;
}
text.setText(result.toString());//將Double 型轉換為String 型
}
}
}
主函式:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Practice();
}
}
總結
提示:這里對文章進行總結:
例如:以上就是今天要講的內容,本文僅僅簡單介紹了pandas的使用,而pandas提供了大量能使我們快速便捷地處理資料的函式和方法,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381250.html
標籤:python
下一篇:R語言ggplot2可視化:擬合二次曲線(quadratic curve)并使用ggplot2進行可視化、可視化兩個回應變數和一個預測變數的二次曲線
