- 相關(guān)推薦
Java編寫計(jì)算器的的常見做法
用java怎么編寫簡易計(jì)算器?有哪幾種編寫方法呢?下面跟yjbys小編一起來看看吧!
界面設(shè)計(jì):用一個(gè)JPanel1 布局是網(wǎng)格 (4*4),分別放置數(shù)字和功能鍵,再用一個(gè)JPanel2 放置顯示區(qū)(JTextArea)1和2,在把JPanel1放入JPanel2中,JPanel2 放入JFrame中;
計(jì)算:
有數(shù)字按鈕按下時(shí),把相應(yīng)的值讀入顯示區(qū)里,當(dāng)有功能鍵按下時(shí),顯示區(qū)清空,在讀入第二操作數(shù),當(dāng)有”=”按下時(shí),調(diào)用相應(yīng)的函數(shù)計(jì)算結(jié)果,并顯示。并激活相應(yīng)的探聽器。
方法1:
import java.awt.*;
import java.awt.event.*;
public class MyCalculator {
private Frame f;
private TextField tf = new TextField(30);
private long result;
private boolean append=false;
private char operator='=';
private Button[] btn=new Button[15];
public MyCalculator() {
initComponent();
}
private void initComponent() {
f = new Frame("My Calculator V1.0");
f.setLayout(new BorderLayout()); //The frame uses BorderLayout
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
Panel centerPanel = new Panel();
centerPanel.setLayout(new GridLayout(5, 3)); //The panel uses GridLayout
NumberListener nl=new NumberListener();
OperatorListener ol=new OperatorListener();
btn[10]=new Button("+");
btn[11]=new Button("-");
btn[12]=new Button("*");
btn[13]=new Button("/");
btn[14]=new Button("=");
for (int i=0;i<=9;i++){
btn[i]=new Button(String.valueOf(i));
centerPanel.add(btn[i]);
btn[i].addActionListener(nl);
if (i%2==1){
centerPanel.add(btn[(i+19)/2]);
btn[(i+19)/2].addActionListener(ol);
}
}
f.add(centerPanel, BorderLayout.CENTER);
Panel northPanel = new Panel();
tf.setEditable(false);
northPanel.add(tf);
f.add(northPanel, BorderLayout.NORTH);
}
public void go() {
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new MyCalculator().go();
}
/**
*采用成員內(nèi)部類方式,實(shí)現(xiàn)探聽器接口,方便訪問主類內(nèi)類內(nèi)部成員。
*此類負(fù)責(zé)數(shù)字按鈕Action事件監(jiān)聽和處理
*/
class NumberListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (!append) {
tf.setText("");
append=true;
}
String s=tf.getText();
s+=e.getActionCommand();
tf.setText(s);
if (!btn[10].isEnabled()){
for(int i=10;i<=14;i++) btn[i].setEnabled(true);
}
}
}
/**
* 成員內(nèi)部類,負(fù)責(zé)操作符按鈕的事件處理
*/
class OperatorListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (!append) return;
for(int i=10;i<=14;i++) btn[i].setEnabled(false);
String s=tf.getText();
long num=Long.parseLong(s);//get the number of textfield
append=false; //set append
switch(operator){
case '+':result+=num;break;
case '-':result-=num;break;
case '*':result*=num;break;
case '/':{
if (num==0) result=0;
else result/=num;
break;
}
case '=':result=num;break;
}
tf.setText(String.valueOf(result));
//set the value of result to textfield
String op=e.getActionCommand();
operator=op.charAt(0); // set operator
}
}
}
方法2:
——————————————————————————————————————————————
package wanwa;
import java.util.*;
public class calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("*****************簡易計(jì)算器****************");
System.out.println("*/t/t/t/t/t*");
System.out.println("* 使用說明: 1.加法 2.減法 3.乘法 4.除法 *");
System.out.println("*/t/t/t/t/t*");
System.out.println("*****************************************");
for(int i=0;i<100;i++){
System.out.print("/n請(qǐng)選擇運(yùn)算規(guī)則:");
int num = input.nextInt();
switch(num){
case 1:
System.out.println("/n******你選擇了加法******/n");
System.out.print("請(qǐng)輸入第1個(gè)加數(shù):");
int jiashu1 = input.nextInt();
System.out.print("請(qǐng)輸入第2個(gè)加數(shù):");
int jiashu2 = input.nextInt();
System.out.println("運(yùn)算結(jié)果為:" + jiashu1 + " + " + jiashu1 + " = " + (jiashu1 + jiashu2));
break;
case 2:
System.out.println("/n******你選擇了減法******/n");
System.out.print("請(qǐng)輸入被減數(shù):");
int jianshu1 = input.nextInt();
System.out.print("請(qǐng)輸入減數(shù):");
int jianshu2 = input.nextInt();
System.out.println("運(yùn)算結(jié)果為:" + jianshu1 + " - " + jianshu2 + " = " + (jianshu1 - jianshu2));
break;
case 3:
System.out.println("/n******你選擇了乘法******/n");
System.out.print("請(qǐng)輸入第1個(gè)因數(shù):");
int chengfa1 = input.nextInt();
System.out.print("請(qǐng)輸入第2個(gè)因數(shù):");
int chengfa2 = input.nextInt();
System.out.println("運(yùn)算結(jié)果為:" + chengfa1 + " * " + chengfa2 + " = " + (chengfa1 * chengfa2));
break;
case 4:
System.out.println("/n******你選擇了除法******/n");
System.out.print("請(qǐng)輸入被除數(shù):");
double chufa1 = input.nextInt();
System.out.print("請(qǐng)輸入除數(shù):");
double chufa2 = input.nextInt();
System.out.println("運(yùn)算結(jié)果為:" + chufa1 + " / " + chufa2 + " = " + (chufa1 / chufa2) + " 余 " + (chufa1 % chufa2));
break;
default:
System.out.println("/n你的選擇有錯(cuò),請(qǐng)重新選擇!");
break;
}
}
}
}
第三種寫法:
——————————————————————————————————————————————
package wanwa;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame {
private Container container;
private GridBagLayout layout;
private GridBagConstraints constraints;
private JTextField displayField;// 計(jì)算結(jié)果顯示區(qū)
private String lastCommand;// 保存+,-,*,/,=命令
private double result;// 保存計(jì)算結(jié)果
private boolean start;// 判斷是否為數(shù)字的開始
public Calculator() {
super("Calculator");
container = getContentPane();
layout = new GridBagLayout();
container.setLayout(layout);
constraints = new GridBagConstraints();
start = true;
result = 0;
lastCommand = "=";
displayField = new JTextField(20);
displayField.setHorizontalAlignment(JTextField.RIGHT);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 4;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 100;
constraints.weighty = 100;
layout.setConstraints(displayField, constraints);
container.add(displayField);
ActionListener = new InsertAction();
ActionListener command = new CommandAction();
// addButton("Backspace", 0, 1, 2, 1, );
// addButton("CE", 2, 1, 1, 1, );
// addButton("C", 3, 1, 1, 1, );
addButton("7", 0, 2, 1, 1, );
addButton("8", 1, 2, 1, 1, );
addButton("9", 2, 2, 1, 1, );
addButton("/", 3, 2, 1, 1, command);
addButton("4", 0, 3, 1, 1, );
addButton("5", 1, 3, 1, 1, );
addButton("6", 2, 3, 1, 1, );
addButton("*", 3, 3, 1, 1, command);
addButton("1", 0, 4, 1, 1, );
addButton("2", 1, 4, 1, 1, );
addButton("3", 2, 4, 1, 1, );
addButton("-", 3, 4, 1, 1, command);
addButton("0", 0, 5, 1, 1, );
// addButton("+/-", 1, 5, 1, 1, );// 只顯示"-"號(hào),"+"沒有實(shí)用價(jià)值
addButton(".", 2, 5, 1, 1, );
addButton("+", 3, 5, 1, 1, command);
addButton("=", 0, 6, 4, 1, command);
this.setResizable(false);
setSize(180, 200);
setVisible(true);
}
private void addButton(String label, int row, int column, int with,
int height, ActionListener listener) {
JButton button = new JButton(label);
constraints.gridx = row;
constraints.gridy = column;
constraints.gridwidth = with;
constraints.gridheight = height;
constraints.fill = GridBagConstraints.BOTH;
button.addActionListener(listener);
layout.setConstraints(button, constraints);
container.add(button);
}
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
displayField.setText("");
start = false;
if (input.equals("+/-"))
displayField.setText(displayField.getText() + "-");
}
if (!input.equals("+/-")) {
if (input.equals("Backspace")) {
String str = displayField.getText();
if (str.length() > 0)
displayField.setText(str.substring(0, str.length() - 1));
} else if (input.equals("CE") || input.equals("C")) {
displayField.setText("0");
start = true;
} else
displayField.setText(displayField.getText() + input);
}
}
}
private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
if (start) {
lastCommand = command;
} else {
calculate(Double.parseDouble(displayField.getText()));
lastCommand = command;
start = true;
}
}
}
public void calculate(double x) {
if (lastCommand.equals("+"))
result += x;
else if (lastCommand.equals("-"))
result -= x;
else if (lastCommand.equals("*"))
result *= x;
else if (lastCommand.equals("/"))
result /= x;
else if (lastCommand.equals("="))
result = x;
displayField.setText("" + result);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
第四種寫法:
——————————————————————————————————————————————
package wanwa;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame {
private Container container;
private GridBagLayout layout;
private GridBagConstraints constraints;
private JTextField displayField;// 計(jì)算結(jié)果顯示區(qū)
private String lastCommand;// 保存+,-,*,/,=命令
private double result;// 保存計(jì)算結(jié)果
private boolean start;// 判斷是否為數(shù)字的開始
public Calculator() {
super("Calculator");
container = getContentPane();
layout = new GridBagLayout();
container.setLayout(layout);
constraints = new GridBagConstraints();
start = true;
result = 0;
lastCommand = "=";
displayField = new JTextField(20);
displayField.setHorizontalAlignment(JTextField.RIGHT);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 4;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 100;
constraints.weighty = 100;
layout.setConstraints(displayField, constraints);
container.add(displayField);
ActionListener = new InsertAction();
ActionListener command = new CommandAction();
// addButton("Backspace", 0, 1, 2, 1, );
// addButton("CE", 2, 1, 1, 1, );
// addButton("C", 3, 1, 1, 1, );
addButton("7", 0, 2, 1, 1, );
addButton("8", 1, 2, 1, 1, );
addButton("9", 2, 2, 1, 1, );
addButton("/", 3, 2, 1, 1, command);
addButton("4", 0, 3, 1, 1, );
addButton("5", 1, 3, 1, 1, );
addButton("6", 2, 3, 1, 1, );
addButton("*", 3, 3, 1, 1, command);
addButton("1", 0, 4, 1, 1, );
addButton("2", 1, 4, 1, 1, );
addButton("3", 2, 4, 1, 1, );
addButton("-", 3, 4, 1, 1, command);
addButton("0", 0, 5, 1, 1, );
// addButton("+/-", 1, 5, 1, 1, );// 只顯示"-"號(hào),"+"沒有實(shí)用價(jià)值
addButton(".", 2, 5, 1, 1, );
addButton("+", 3, 5, 1, 1, command);
addButton("=", 0, 6, 4, 1, command);
this.setResizable(false);
setSize(180, 200);
setVisible(true);
}
private void addButton(String label, int row, int column, int with,
int height, ActionListener listener) {
JButton button = new JButton(label);
constraints.gridx = row;
constraints.gridy = column;
constraints.gridwidth = with;
constraints.gridheight = height;
constraints.fill = GridBagConstraints.BOTH;
button.addActionListener(listener);
layout.setConstraints(button, constraints);
container.add(button);
}
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
displayField.setText("");
start = false;
if (input.equals("+/-"))
displayField.setText(displayField.getText() + "-");
}
if (!input.equals("+/-")) {
if (input.equals("Backspace")) {
String str = displayField.getText();
if (str.length() > 0)
displayField.setText(str.substring(0, str.length() - 1));
} else if (input.equals("CE") || input.equals("C")) {
displayField.setText("0");
start = true;
} else
displayField.setText(displayField.getText() + input);
}
}
}
private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
if (start) {
lastCommand = command;
} else {
calculate(Double.parseDouble(displayField.getText()));
lastCommand = command;
start = true;
}
}
}
public void calculate(double x) {
if (lastCommand.equals("+"))
result += x;
else if (lastCommand.equals("-"))
result -= x;
else if (lastCommand.equals("*"))
result *= x;
else if (lastCommand.equals("/"))
result /= x;
else if (lastCommand.equals("="))
result = x;
displayField.setText("" + result);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
【Java編寫計(jì)算器的的常見做法】相關(guān)文章:
Java編程常見問題匯總08-15
科學(xué)計(jì)算器有哪些功能08-12
監(jiān)理通知編寫的誤區(qū)05-15
學(xué)習(xí)java技巧10-31
高效編寫JavaScript代碼的技巧08-29
涼皮做法的做法04-18
燕窩的做法-燕窩做法大全08-29
花甲的做法-炒花甲的做法08-29