用java寫的計算器的程序,主要是通過控制臺輸入,主要方法是使用scanner類來接收用戶從鍵盤輸入的一個算式,通過分解算式,存入兩個字符串,判斷中間的的符號,進行相應計算,如下代碼:
站在用戶的角度思考問題,與客戶深入溝通,找到丹寨網站設計與丹寨網站推廣的解決方案,憑借多年的經驗,讓設計與互聯(lián)網技術結合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:網站設計制作、做網站、企業(yè)官網、英文網站、手機端網站、網站推廣、空間域名、網頁空間、企業(yè)郵箱。業(yè)務覆蓋丹寨地區(qū)。
System.out.println("-----------------------------------");
System.out.println("請輸入一個算術表達式,如:45*23");
Scanner?in?=?new?Scanner(System.in);//接收用戶從鍵盤輸入的字符
String?str?=?in.nextLine();
StringBuffer?buffer?=?new?StringBuffer();//保存左側的數字
StringBuffer?buffer1?=?new?StringBuffer();//保存右側的數字
char?t?=?'?';//保存運算符
for?(int?i?=?0;?i??str.length();?i++)?{
if?(str.charAt(i)?==?'+'?||?str.charAt(i)?==?'-'
||?str.charAt(i)?==?'*'?||?str.charAt(i)?==?'/')?{
t?=?str.charAt(i);//識別是什么運算符
for?(int?j?=?i?+?1;?j??str.length();?j++)?{
buffer1.append(str.charAt(j));
}
break;
}?else?{
buffer.append(str.charAt(i));
}
}
String?c?=?buffer.toString();
String?d?=?buffer1.toString();
double?a?=?Double.parseDouble(c);
double?b?=?Double.parseDouble(d);
double?sum?=?0;
if?(t?==?'+')?{
sum?=?a?+?b;
}
if?(t?==?'-')?{
sum?=?a?-?b;
}
if?(t?==?'*')?{
sum?=?a?*?b;
}
if?(t?==?'/')?{
sum?=?a?/?b;
}
System.out.println("程序運算...");
System.out.println(c+t+d+"="+sum);
System.out.print("-----------------------------------");
運行結果如下:
import java.awt.BorderLayout; import java.awt.Color; 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.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.TitledBorder; //導包 public class Jisuanqi extends JFrame implements ActionListener { //繼承JFrame 實現(xiàn)事件監(jiān)聽 private JTextField reasult; private JButton btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnAC, btnAdd, btnSub, btnReasult, btnD, btnAbout, btnCancel; private boolean add, sub, end, s, c; private String str; private double num1, num2; public Jisuanqi() { //構造屬性 JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); TitledBorder tb = new TitledBorder("輸出"); tb.setTitleColor(Color.BLUE); //標題邊框底端線 設置顏色 btnAbout = new JButton(" 關于 "); btnCancel = new JButton("Cancel"); //兩個按鈕 btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { System.exit(0); } }); //給Cancel添加事件監(jiān)聽 當鼠標點擊時 程序結束 btnAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { JOptionPane.showMessageDialog(null, "黃蓋!!", "消息", JOptionPane.INFORMATION_MESSAGE); } //給“關于”添加事件監(jiān)聽 當鼠標點擊時 彈出對話框 顯示黃蓋 }); p3.add(btnAbout); p3.add(btnCancel); // JPanel p4=new JPanel(); // JPanel p5=new JPanel(); // reasult.setBorder(tb); reasult = new JTextField("0", 20); reasult.setEditable(false); //設置不能修改 reasult.setHorizontalAlignment(JTextField.RIGHT); // 設置文本的水平對齊方式。 reasult.setForeground(Color.BLUE); //顏色 p1.setBorder(tb); p1.add(reasult); btn0 = new JButton("0"); btn0.addActionListener(this); btn1 = new JButton("1"); btn1.addActionListener(this); btn2 = new JButton("2"); btn2.addActionListener(this); btn3 = new JButton("3"); btn3.addActionListener(this); btn4 = new JButton("4"); btn4.addActionListener(this); btn5 = new JButton("5"); btn5.addActionListener(this); btn6 = new JButton("6"); btn6.addActionListener(this); btn7 = new JButton("7"); btn7.addActionListener(this); btn8 = new JButton("8"); btn8.addActionListener(this); btn9 = new JButton("9"); btn9.addActionListener(this); btnD = new JButton("."); btnD.addActionListener(this); btnD.setForeground(Color.RED); btnAC = new JButton("AC"); btnAC.addActionListener(this); btnAC.setBackground(Color.PINK); btnAdd = new JButton("+"); btnAdd.addActionListener(this); btnAdd.setForeground(Color.BLUE); btnSub = new JButton("—"); btnSub.addActionListener(this); btnSub.setForeground(Color.BLUE); btnReasult = new JButton("="); btnReasult.addActionListener(this); btnReasult.setForeground(Color.RED); //事件監(jiān)聽 + 顏色 p2.add(btn1); p2.add(btn2); p2.add(btn3); p2.add(btn4); p2.add(btn5); p2.add(btn6); p2.add(btn7); p2.add(btn8); p2.add(btn9); p2.add(btn0); p2.add(btnD); p2.add(btnAC); p2.add(btnAdd); p2.add(btnSub); p2.add(btnReasult); //面板上添加按鈕 p2.setLayout(new GridLayout(5, 3)); //面板上設置對齊方式 add(p1, BorderLayout.NORTH); add(p2, BorderLayout.CENTER); add(p3, BorderLayout.SOUTH); //將p1 p2 p3 面板對象添加到JFrame } public void num(int i) { String s = null; s = String.valueOf(i); if (end) { // 如果數字輸入結束,則將文本框置零,重新輸入 reasult.setText("0"); end = false; } if ((reasult.getText()).equals("0")) { // 如果文本框的內容為零,則覆蓋文本框的內容 reasult.setText(s); } else { // 如果文本框的內容不為零,則在內容后面添加數字 str = reasult.getText() + s; reasult.setText(str); } }/* * * String s=null; * * s=String.valueOf(i); * * str=reasult.getText()+s; * * reasult.setText(str); * * } */ public void actionPerformed(ActionEvent e) { if (e.getSource() == btn1) num(1); else if (e.getSource() == btn2) num(2); else if (e.getSource() == btn3) num(3); else if (e.getSource() == btn4) num(4); else if (e.getSource() == btn5) num(5); else if (e.getSource() == btn6) num(6); else if (e.getSource() == btn7) num(7); else if (e.getSource() == btn8) num(8); else if (e.getSource() == btn9) num(9); else if (e.getSource() == btn0) num(0); else if (e.getSource() == btnAdd) { sign(1); btnD.setEnabled(true); } else if (e.getSource() == btnSub) { sign(2); btnD.setEnabled(true); } else if (e.getSource() == btnAC) { btnD.setEnabled(true); reasult.setText("0"); } else if (e.getSource() == btnD) { str = reasult.getText(); str += "."; reasult.setText(str); btnD.setEnabled(false); } else if (e.getSource() == btnReasult) { btnD.setEnabled(true); num2 = Double.parseDouble(reasult.getText()); if (add) { num1 = num1 + num2; } else if (sub) { num1 = num1 - num2; } reasult.setText(String.valueOf(num1)); end = true; } } public void sign(int s) { if (s == 1) { add = true; sub = false; } else if (s == 2) { add = false; sub = true; } num1 = Double.parseDouble(reasult.getText()); end = true; } //設計計算的過程 public static void main(String[] args) { Jisuanqi j = new Jisuanqi(); j.setTitle("+/-簡易計算器"); j.setLocation(500, 280); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //默認關閉可以關閉程序 j.setResizable(false); j.pack(); j.setVisible(true); } } 這個計算機,絕對讓你滿意
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
/**
* 我的計算器。Cheshi 繼承于 JFrame,是計算器的界面
c*/
public class Cheshi extends JFrame {
private Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox = new JTextField("0");
private CalculatorCore core = new CalculatorCore();
private ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
String label = b.getText();
String result = core.process(label);
textbox.setText(result);
}
};
public Cheshi(String title) throws HeadlessException {
super(title); // 調用父類構造方法
setupFrame(); // 調整窗體屬性
setupControls(); // 創(chuàng)建控件
}
private void setupControls() {
setupDisplayPanel(); // 創(chuàng)建文本面板
setupButtonsPanel(); // 創(chuàng)建按鈕面板
}
// 創(chuàng)建按鈕面板并添加按鈕
private void setupButtonsPanel() {
JPanel panel = new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]{
"7", "8", "9", "+", "C",
"4", "5", "6", "-", "CE",
"1", "2", "3", "*", "", // 空字符串表示這個位置沒有按鈕
"0", ".", "=", "/", ""
});
this.add(panel, BorderLayout.CENTER);
}
/**
* 在指定的面板上創(chuàng)建按鈕
*
* @param panel 要創(chuàng)建按鈕的面板
* @param labels 按鈕文字
*/
private void createButtons(JPanel panel, String[] labels) {
for (String label : labels) {
// 如果 label 為空,則表示創(chuàng)建一個空面板。否則創(chuàng)建一個按鈕。
if (label.equals("")) {
panel.add(new JPanel());
} else {
JButton b = new JButton(label);
b.addActionListener(listener); // 為按鈕添加偵聽器
panel.add(b);
}
}
}
// 設置顯示面板,用一個文本框來作為計算器的顯示部分。
private void setupDisplayPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
// 調整文本框
private void setupTextbox() {
textbox.setHorizontalAlignment(JTextField.RIGHT); // 文本右對齊
textbox.setEditable(false); // 文本框只讀
textbox.setBackground(Color.white); // 文本框背景色為白色
}
// 調整窗體
private void setupFrame() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 當窗體關閉時程序結束
this.setLocation(100, 50); // 設置窗體顯示在桌面上的位置
this.setSize(300, 200); // 設置窗體大小
this.setResizable(false); // 窗體大小固定
}
// 程序入口
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Cheshi frame = new Cheshi("我的計算器");
frame.setVisible(true); // 在桌面上顯示窗體
}
}
/**
* 計算器核心邏輯。這個邏輯只能處理 1~2 個數的運算。
*/
class CalculatorCore {
private String displayText = "0"; // 要顯示的文本
boolean reset = true;
private BigDecimal number1, number2;
private String operator;
private HashMapString, Operator operators = new HashMapString, Operator();
private HashMapString, Processor processors = new HashMapString, Processor();
CalculatorCore() {
setupOperators();
setupProcessors();
}
// 為每種命令添加處理方式
private void setupProcessors() {
processors.put("[0-9]", new Processor() {
public void calculate(String command) {
numberClicked(command);
}
});
processors.put("\\.", new Processor() {
public void calculate(String command) {
dotClicked();
}
});
processors.put("=", new Processor() {
public void calculate(String command) {
equalsClicked();
}
});
processors.put("[+\\-*/]", new Processor() {
public void calculate(String command) {
operatorClicked(command);
}
});
processors.put("C", new Processor() {
public void calculate(String command) {
clearClicked();
}
});
processors.put("CE", new Processor() {
public void calculate(String command) {
clearErrorClicked();
}
});
}
// 為每種 operator 添加處理方式
private void setupOperators() {
operators.put("+", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.add(number2);
}
});
operators.put("-", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.subtract(number2);
}
});
operators.put("*", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.multiply(number2);
}
});
operators.put("/", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.divide(number2, 30, RoundingMode.HALF_UP);
}
});
}
// 根據命令處理。這里的命令實際上就是按鈕文本。
public String process(String command) {
for (String pattern : processors.keySet()) {
if (command.matches(pattern)) {
processors.get(pattern).calculate(command);
break;
}
}
return displayText;
}
// 當按下 CE 時
private void clearErrorClicked() {
if (operator == null) {
number1 = null;
} else {
number2 = null;
}
displayText = "0";
reset = true;
}
// 當按下 C 時,將計算器置為初始狀態(tài)。
private void clearClicked() {
number1 = null;
number2 = null;
operator = null;
displayText = "0";
reset = true;
}
// 當按下 = 時
private void equalsClicked() {
calculateResult();
number1 = null;
number2 = null;
operator = null;
reset = true;
}
// 計算結果
private void calculateResult() {
number2 = new BigDecimal(displayText);
Operator oper = operators.get(operator);
if (oper != null) {
BigDecimal result = oper.process(number1, number2);
displayText = result.toString();
}
}
// 當按下 +-*/ 時(這里也可以擴展成其他中間操作符)
private void operatorClicked(String command) {
if (operator != null) {
calculateResult();
}
number1 = new BigDecimal(displayText);
operator = command;
reset = true;
}
// 當按下 . 時
private void dotClicked() {
if (displayText.indexOf(".") == -1) {
displayText += ".";
} else if (reset) {
displayText = "0.";
}
reset = false;
}
// 當按下 0-9 時
private void numberClicked(String command) {
if (reset) {
displayText = command;
} else {
displayText += command;
}
reset = false;
}
// 運算符處理接口
interface Operator {
BigDecimal process(BigDecimal number1, BigDecimal number2);
}
// 按鈕處理接口
interface Processor {
void calculate(String command);
}
}
import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
public class MyCalculator extends JFrame {
private Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox = new JTextField("0");
private CalculatorCore core = new CalculatorCore();
private ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
String label = b.getText();
String result = core.process(label);
textbox.setText(result);
}
};
public MyCalculator(String title) throws HeadlessException {
super(title); // 調用父類構造方法
setupFrame(); // 調整窗體屬性
setupControls(); // 創(chuàng)建控件
}
private void setupControls() {
setupDisplayPanel(); // 創(chuàng)建文本面板
setupButtonsPanel(); // 創(chuàng)建按鈕面板
}
// 創(chuàng)建按鈕面板并添加按鈕
private void setupButtonsPanel() {
JPanel panel = new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]{
"7", "8", "9", "+", "C",
"4", "5", "6", "-", "CE",
"1", "2", "3", "*", "", // 空字符串表示這個位置沒有按鈕
"0", ".", "=", "/", ""
});
this.add(panel, BorderLayout.CENTER);
}
/**
* 在指定的面板上創(chuàng)建按鈕
*
* @param panel 要創(chuàng)建按鈕的面板
* @param labels 按鈕文字
*/
private void createButtons(JPanel panel, String[] labels) {
for (String label : labels) {
// 如果 label 為空,則表示創(chuàng)建一個空面板。否則創(chuàng)建一個按鈕。
if (label.equals("")) {
panel.add(new JPanel());
} else {
JButton b = new JButton(label);
b.addActionListener(listener); // 為按鈕添加偵聽器
panel.add(b);
}
}
}
// 設置顯示面板,用一個文本框來作為計算器的顯示部分。
private void setupDisplayPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
// 調整文本框
private void setupTextbox() {
textbox.setHorizontalAlignment(JTextField.RIGHT); // 文本右對齊
textbox.setEditable(false); // 文本框只讀
textbox.setBackground(Color.white); // 文本框背景色為白色
}
// 調整窗體
private void setupFrame() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 當窗體關閉時程序結束
this.setLocation(100, 50); // 設置窗體顯示在桌面上的位置
this.setSize(300, 200); // 設置窗體大小
this.setResizable(false); // 窗體大小固定
}
// 程序入口
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
MyCalculator frame = new MyCalculator("我的計算器");
frame.setVisible(true); // 在桌面上顯示窗體
}
}
/**
* 計算器核心邏輯。這個邏輯只能處理 1~2 個數的運算。
*/
class CalculatorCore {
private String displayText = "0"; // 要顯示的文本
boolean reset = true;
private BigDecimal number1, number2;
private String operator;
private HashMapString, Operator operators = new HashMapString, Operator();
private HashMapString, Processor processors = new HashMapString, Processor();
CalculatorCore() {
setupOperators();
setupProcessors();
}
// 為每種命令添加處理方式
private void setupProcessors() {
processors.put("[0-9]", new Processor() {
public void calculate(String command) {
numberClicked(command);
}
});
processors.put("\\.", new Processor() {
public void calculate(String command) {
dotClicked();
}
});
processors.put("=", new Processor() {
public void calculate(String command) {
equalsClicked();
}
});
processors.put("[+\\-*/]", new Processor() {
public void calculate(String command) {
operatorClicked(command);
}
});
processors.put("C", new Processor() {
public void calculate(String command) {
clearClicked();
}
});
processors.put("CE", new Processor() {
public void calculate(String command) {
clearErrorClicked();
}
});
}
// 為每種 operator 添加處理方式
private void setupOperators() {
operators.put("+", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.add(number2);
}
});
operators.put("-", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.subtract(number2);
}
});
operators.put("*", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.multiply(number2);
}
});
operators.put("/", new Operator() {
public BigDecimal process(BigDecimal number1, BigDecimal number2) {
return number1.divide(number2, 30, RoundingMode.HALF_UP);
}
});
}
// 根據命令處理。這里的命令實際上就是按鈕文本。
public String process(String command) {
for (String pattern : processors.keySet()) {
if (command.matches(pattern)) {
processors.get(pattern).calculate(command);
break;
}
}
return displayText;
}
// 當按下 CE 時
private void clearErrorClicked() {
if (operator == null) {
number1 = null;
} else {
number2 = null;
}
displayText = "0";
reset = true;
}
// 當按下 C 時,將計算器置為初始狀態(tài)。
private void clearClicked() {
number1 = null;
number2 = null;
operator = null;
displayText = "0";
reset = true;
}
// 當按下 = 時
private void equalsClicked() {
calculateResult();
number1 = null;
number2 = null;
operator = null;
reset = true;
}
// 計算結果
private void calculateResult() {
number2 = new BigDecimal(displayText);
Operator oper = operators.get(operator);
if (oper != null) {
BigDecimal result = oper.process(number1, number2);
displayText = result.toString();
}
}
// 當按下 +-*/ 時(這里也可以擴展成其他中間操作符)
private void operatorClicked(String command) {
if (operator != null) {
calculateResult();
}
number1 = new BigDecimal(displayText);
operator = command;
reset = true;
}
// 當按下 . 時
private void dotClicked() {
if (displayText.indexOf(".") == -1) {
displayText += ".";
} else if (reset) {
displayText = "0.";
}
reset = false;
}
// 當按下 0-9 時
private void numberClicked(String command) {
if (reset) {
displayText = command;
} else {
displayText += command;
}
reset = false;
}
// 運算符處理接口
interface Operator {
BigDecimal process(BigDecimal number1, BigDecimal number2);
}
// 按鈕處理接口
interface Processor {
void calculate(String command);
}
}