學(xué)java的時(shí)候自己編的,很簡(jiǎn)單,能夠連續(xù)輸入計(jì)算式后進(jìn)行計(jì)算
成都創(chuàng)新互聯(lián)長期為1000+客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為臨潁企業(yè)提供專業(yè)的成都網(wǎng)站建設(shè)、網(wǎng)站制作,臨潁網(wǎng)站改版等技術(shù)服務(wù)。擁有10余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**簡(jiǎn)易計(jì)算器,能夠進(jìn)行簡(jiǎn)單的計(jì)算
*
* @see 2008.12.9
*/
public class CalculatorA
implements ActionListener{
private JFrame frame;
private JTextField field;
private JButton[] allButtons;
private JButton clearButton;
// private JButton backButton;
String result="";//保存結(jié)果
StringBuilder sb = new StringBuilder();//保存要進(jìn)行的計(jì)算式
int x = 0; //用來判斷上一次的事件類型
String str = "123+456-789*0.=/";
ArrayListString arrayList = new ArrayListString();//保存計(jì)算式,通過方法進(jìn)行運(yùn)算
public CalculatorA(){
frame = new JFrame("我的計(jì)算器v1.1");
frame.setLocation(300,300);
field = new JTextField(25);
allButtons = new JButton[16];
for(int i=0;iallButtons.length;i++){
allButtons[i]= new JButton(str.substring(i,i+1));
}
clearButton = new JButton("CLEAR");
// backButton = new JButton("——");
init();
setFondAndColor();
addEventHander();
}
public void init(){
frame.setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(field);
for(int i=0;iallButtons.length;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
//southPanel.add(backButton);
frame.add(northPanel,BorderLayout.NORTH);
frame.add(centerPanel,BorderLayout.CENTER);
frame.add(southPanel,BorderLayout.SOUTH);
}
//設(shè)置輸入字體
public void setFondAndColor(){
field.setFont(new Font("宋體",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
field.setForeground(Color.RED);
//設(shè)置字體從右起始
field.setHorizontalAlignment(JTextField.RIGHT);
}
public void showMi(){
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void addEventHander(){
for(int i=0;iallButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
// backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得當(dāng)前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //當(dāng)x為0時(shí)表示還沒有進(jìn)行輸入
result=str;
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 1){
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 2){
sb.delete(0,sb.length());
result = result+str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 3){
result = str;
sb.delete(0,sb.length());
arrayList.clear();
field.setText(str);
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
result = str;
sb.append(str);
field.setText(str);
x = 1;
}
else{
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
}
else if("+*-/".indexOf(str)!=-1){
if(x == 0){
field.setText("");
x = 2;
}
else if(x == 1){
result = result + str;
arrayList.add(sb.toString());
arrayList.add(str);
sb.append(str);
field.setText(result);
x = 2;
}
else if(x == 2){
x = 2;
}
else if(x == 3){
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 2;
}
else{
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
}
else if("=".equals(str)){
if(x == 0){
field.setText("0");
arrayList.clear();
result = "0";
x = 3;
}
else if(x == 1){
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("數(shù)據(jù)格式異常");
x = 0;
}
}
else if(x == 2){
field.setText("數(shù)據(jù)格式錯(cuò)誤.....");
arrayList.clear();
x = 0;
}
else if(x == 3){
field.setText(result);
x = 3;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 3;
}
else {
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("數(shù)據(jù)格式異常");
x = 0;
}
}
}
else if("CLEAR".equals(str)){
arrayList.clear();
field.setText("0");
arrayList.add("0");
x = 4;
}
else{
if(result.length()1){
result = result.substring(0,result.length()-1);
if(sb.length()0){
sb.delete(sb.length()-1,sb.length());
}
else {
sb.delete(0,1);
}
field.setText(result);
x = 5;
}
else{
result = "";
sb.delete(0,sb.length());
arrayList.clear();
field.setText("0");
x = 0;
}
}
}
public static ArrayListString getResult(ArrayListString list){
String res = null;
String[] s = {"/","*","-","+"};
int i=0;
if(list.size()1){
for(;is.length;){
if(s[i].equals("/")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j+1)));
//本地的數(shù)據(jù)格式
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("*")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("-")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getNumberInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else {
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))+Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
}
}
return list;
}
//對(duì)數(shù)字字符串進(jìn)行排除不必要符號(hào)
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;kc.length;k++){
c[k] = res.charAt(k);
}
for(int k=0;kc.length;k++){
if((c[k]= '0' c[k]= '9')|| c[k] == '.'){
s_temp += c[k];
}
}
return s_temp;
}
public static void main(String[] args){
new CalculatorA().showMi();
}
}
然后 通過輸入 顯示結(jié)果,比如說:
以下是上圖計(jì)算器的代碼:
package?Computer;
import?java.awt.BorderLayout;
import?java.awt.Color;
import?java.awt.Container;
import?java.awt.Font;
import?java.awt.GridLayout;
import?java.awt.event.ActionEvent;
import?java.awt.event.ActionListener;
import?java.util.Stack;
import?javax.swing.JApplet;
import?javax.swing.JButton;
import?javax.swing.JFrame;
import?javax.swing.JPanel;
import?javax.swing.JTextField;
public?class?Count?extends?JApplet?implements?ActionListener
{
/**
*
*/
private?static?final?long?serialVersionUID?=?1L;
private?JTextField?textField?=?new?JTextField("請(qǐng)輸入");
String?operator?=?"";//操作
String?input?=?"";//輸入的?式子
boolean?flag?=??true;
//??boolean?flag1?=?true;
//??boolean?flag2?=?true;
public?void?init()//覆寫Applet里邊的init方法
{
Container?C?=?getContentPane();
JButton?b[]?=?new?JButton[16];
JPanel?panel?=?new?JPanel();
C.add(textField,?BorderLayout.NORTH);
C.add(panel,BorderLayout.CENTER);
panel.setLayout(new?GridLayout(4,?4,5,5));
String?name[]={"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};//設(shè)置?按鈕
for(int?i=0;i16;i++)//添加按鈕
{
b[i]?=?new?JButton(name[i]);
b[i].setBackground(new?Color(192,192,192));
b[i].setForeground(Color.BLUE);//數(shù)字鍵?設(shè)置為?藍(lán)顏色
if(i%4==3)
b[i].setForeground(Color.RED);
b[i].setFont(new?Font("宋體",Font.PLAIN,16));//設(shè)置字體格式
panel.add(b[i]);
b[i].addActionListener(this);
}
b[13].setForeground(Color.RED);//非數(shù)字鍵,即運(yùn)算鍵設(shè)置為紅顏色
b[13].setForeground(Color.RED);
}
public?void?actionPerformed(ActionEvent?e)
{
int?cnt?=?0;
String?actionCommand?=?e.getActionCommand();
if(actionCommand.equals("+")||actionCommand.equals("-")||actionCommand.equals("*")?||actionCommand.equals("/"))
input?+="?"+actionCommand+"?";//設(shè)置輸入,把輸入的樣式改成?需要的樣子
else?if(actionCommand.equals("C"))
input?=?"";
else?if(actionCommand.equals("="))//當(dāng)監(jiān)聽到等號(hào)時(shí),則處理?input
{
input+=?"="+compute(input);
textField.setText(input);
input="";
cnt?=?1;
}
else
input?+=?actionCommand;//數(shù)字為了避免多位數(shù)的輸入?不需要加空格
if(cnt==0)
textField.setText(input);
}
private?String?compute(String?input)//即1237?的?樣例
{
String?str[];
str?=?input.split("?");
StackDouble?s?=?new?StackDouble();
double?m?=?Double.parseDouble(str[0]);
s.push(m);
for(int?i=1;istr.length;i++)
{
if(i%2==1)
{
if(str[i].compareTo("+")==0)
{
double?help?=?Double.parseDouble(str[i+1]);
s.push(help);
}
if(str[i].compareTo("-")==0)
{
double?help?=?Double.parseDouble(str[i+1]);
s.push(-help);
}
if(str[i].compareTo("*")==0)
{
double?help?=?Double.parseDouble(str[i+1]);
double?ans?=?s.peek();//取出棧頂元素
s.pop();//消棧
ans*=help;
s.push(ans);
}
if(str[i].compareTo("/")==0)
{
double?help?=?Double.parseDouble(str[i+1]);
double?ans?=?s.peek();
s.pop();
ans/=help;
s.push(ans);
}
}
}
double?ans?=?0d;
while(!s.isEmpty())
{
ans+=s.peek();
s.pop();
}
String?result?=?String.valueOf(ans);
return?result;
}
public?static?void?main(String?args[])
{
JFrame?frame?=?new?JFrame("Count");
Count?applet?=?new?Count();
frame.getContentPane().add(applet,?BorderLayout.CENTER);
applet.init();//applet的init方法
applet.start();//線程開始
frame.setSize(350,?400);//設(shè)置窗口大小
frame.setVisible(true);//設(shè)置窗口可見
}
}
簡(jiǎn)單寫了下,代碼如下請(qǐng)參照:
/**
*?計(jì)算器類
*?
*?@author?Administrator
*
*/
public?class?Calculator?extends?JFrame?implements?ActionListener?{
private?static?final?long?serialVersionUID?=?3868243398506940702L;
//?文本框
private?JTextField?result;
//?按鈕數(shù)組
private?JButton[]?buttons;
//?按鈕文本
private?final?String[]?characters?=?{?"7",?"8",?"9",?"/",?"4",?"5",?"6",
"*",?"1",?"2",?"3",?"-",?"0",?".",?"=",?"+"?};
//?是否為第一個(gè)輸入的數(shù)字
private?boolean?isFirstDigit?=?true;
//?運(yùn)算結(jié)果
private?double?resultNum?=?0.0;
//?運(yùn)算符
private?String?operator?=?"=";
public?Calculator(String?title)?{
//?設(shè)置標(biāo)題欄
super(title);
//?初始化各組件
init();
//?注冊(cè)各組件監(jiān)聽器
registerListener();
//?顯示窗體
setVisible(true);
}
/**
*?初始化各組件
*/
private?void?init()?{
//?常用屬性初始化
setSize(220,?200);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
/*?文本框?qū)ο蟪跏蓟?*/
result?=?new?JTextField("0");
//?文本右對(duì)齊
result.setHorizontalAlignment(JTextField.RIGHT);
//?設(shè)置是否可編輯
result.setEditable(false);
/*?按鈕初始化?*/
buttons?=?new?JButton[characters.length];
for?(int?i?=?0;?i??buttons.length;?i++)?{
buttons[i]?=?new?JButton(characters[i]);
buttons[i].setFocusable(false);?//?不允許按鈕定位焦點(diǎn)
}
/*?將文本框與按鈕添加到窗體中?*/
add(result,?BorderLayout.NORTH);
JPanel?pnl?=?new?JPanel(new?GridLayout(4,?4,?5,?5));
for?(JButton?jButton?:?buttons)?{
pnl.add(jButton);
}
add(pnl);
this.getContentPane().setFocusable(true);
}
/**
*?注冊(cè)監(jiān)聽器
*/
private?void?registerListener()?{
for?(JButton?jButton?:?buttons)?{
jButton.addActionListener(this);
}
//?注冊(cè)鍵盤事件
this.getContentPane().addKeyListener(new?KeyAdapter()?{
@Override
public?void?keyPressed(KeyEvent?e)?{
String?text?=?String.valueOf(e.getKeyChar());
if?(Character.isDigit(text.charAt(0))?||?".".equals(text))?{?//?數(shù)字或小數(shù)點(diǎn)
handleNumber(text);
}?else?if?("+-*/=".indexOf(text)?!=?-1)?{?//?運(yùn)算符
handleOperator(text);
}?else?if?(e.getKeyCode()?==?8)?{?//?退格鍵
String?tmp?=?result.getText().trim();
if?(tmp.length()?==?1)?{
result.setText("0");
isFirstDigit?=?true;
}?else?{
result.setText(tmp.substring(0,?tmp.length()?-?1));
}
}
}
});
}
@Override
public?void?actionPerformed(ActionEvent?e)?{
JButton?btn?=?(JButton)?e.getSource();
String?text?=?btn.getText().trim();
if?(Character.isDigit(text.charAt(0))?||?".".equals(text))?{?//?處理數(shù)字和小數(shù)點(diǎn)
handleNumber(text);
}?else?{?//?處理運(yùn)算符
handleOperator(text);
}
}
/**
*?處理數(shù)字和小數(shù)點(diǎn)
*?
*?@param?text
*/
private?void?handleNumber(String?text)?{
if?(isFirstDigit)?{?//?第一次輸入
if?(".".equals(text))?{
this.result.setText("0.");
}?else?{
this.result.setText(text);
}
}?else?if?("0".equals(text)??"0".equals(this.result.getText()))?{
isFirstDigit?=?true;
return;
}?else?if?(".".equals(text)??this.result.getText().indexOf(".")?==?-1)?{
this.result.setText(this.result.getText()?+?".");
}?else?if?(!".".equals(text))?{
this.result.setText(this.result.getText()?+?text);
}
isFirstDigit?=?false;
}
/**
*?處理運(yùn)算符
*?
*?@param?text
*/
private?void?handleOperator(String?text)?{
switch?(operator)?{?//?處理各項(xiàng)運(yùn)算??適用于JDK1.7版本的
case?"+":
resultNum?+=?Double.parseDouble(this.result.getText());
break;
case?"-":
resultNum?-=?Double.parseDouble(this.result.getText());
break;
case?"*":
resultNum?*=?Double.parseDouble(this.result.getText());
break;
case?"/":
resultNum?/=?Double.parseDouble(this.result.getText());
break;
case?"=":
resultNum?=?Double.parseDouble(this.result.getText());
break;
}
//?將文本框的值修改為運(yùn)算結(jié)果
this.result.setText(String.valueOf(resultNum));
//?將點(diǎn)擊的運(yùn)算符放入operator保存
operator?=?text;
//?下一個(gè)數(shù)字第一次點(diǎn)擊
isFirstDigit?=?true;
}
public?static?void?main(String[]?args)?{
?new?Calculator("My?Calculator");
?}
}
運(yùn)行結(jié)果如下: