求一个JAVA简单的计算器代码 不要界面和按钮的那种

swuxd 2012-11-24 01:13:27
谢谢
...全文
1584 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
fuxisong502 2012-11-27
  • 打赏
  • 举报
回复
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JTextField; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Cacuclator extends JFrame { double x, y; int k; private JPanel contentPane; private JTextField textField; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Cacuclator frame = new Cacuclator(); frame.setResizable(false); frame.setVisible(true); frame.setTitle("计算器"); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Cacuclator() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBounds(10, 62, 60, 190); contentPane.add(panel); panel.setLayout(new GridLayout(4, 0, 1, 0)); JButton btnNewButton = new JButton("New button"); panel.add(btnNewButton); JButton btnNewButton_2 = new JButton("New button"); panel.add(btnNewButton_2); JButton btnNewButton_1 = new JButton("New button"); panel.add(btnNewButton_1); JButton 正负 = new JButton("+/-"); 正负.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); //s = s.replaceAll("\\D+", ""); StringBuffer k = new StringBuffer(s); k.append("-"); String u = new String(k); textField.setText(u); } }); panel.add(正负); JPanel panel_1 = new JPanel(); panel_1.setBounds(73, 49, 351, 50); contentPane.add(panel_1); panel_1.setLayout(new GridLayout(1, 0, 3, 0)); JButton BLACKSPACE = new JButton("BLACKSPACE"); BLACKSPACE.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); panel_1.add(BLACKSPACE); JButton MC = new JButton("MC"); MC.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); panel_1.add(MC); JButton C = new JButton("C"); C.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { textField.setText(""); } }); panel_1.add(C); JPanel panel_2 = new JPanel(); panel_2.setBounds(80, 109, 344, 143); contentPane.add(panel_2); panel_2.setLayout(new GridLayout(4, 0, 4, 0)); JButton b7 = new JButton("7"); b7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("7"); String u = new String(k); textField.setText(u); } }); panel_2.add(b7); JButton b8 = new JButton("8"); b8.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("8"); String u = new String(k); textField.setText(u); } }); panel_2.add(b8); JButton b9 = new JButton("9"); b9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("9"); String u = new String(k); textField.setText(u); } }); panel_2.add(b9); JButton 加 = new JButton("+"); 加.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = textField.getText(); x=Double.parseDouble(s); if(s.contains("+")||s.contains("-")||s.contains("*")||s.contains("/")){ StringBuffer m=new StringBuffer(s); m.delete(m.length()-1, m.length()); } textField.setText("+"); k = 0; } }); panel_2.add(加); JButton b4 = new JButton("4"); b4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("4"); String u = new String(k); textField.setText(u); } }); panel_2.add(b4); JButton b5 = new JButton("5"); b5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("5"); String u = new String(k); textField.setText(u); } }); panel_2.add(b5); JButton b6 = new JButton("6"); b6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("6"); String u = new String(k); textField.setText(u); } }); panel_2.add(b6); JButton 减 = new JButton("-"); 减.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = textField.getText(); x=Double.parseDouble(s); if(s.contains("+")||s.contains("-")||s.contains("*")||s.contains("/")){ StringBuffer m=new StringBuffer(s); m.delete(m.length()-1, m.length()); } textField.setText("-"); k =1; } }); panel_2.add(减); JButton b1 = new JButton("1"); b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("1"); String u = new String(k); textField.setText(u); } }); panel_2.add(b1); JButton b2 = new JButton("2"); b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("2"); String u = new String(k); textField.setText(u); } }); panel_2.add(b2); JButton b3 = new JButton("3"); b3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("3"); String u = new String(k); textField.setText(u); } }); panel_2.add(b3); JButton 乘 = new JButton("*"); 乘.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = textField.getText(); x=Double.parseDouble(s); if(s.contains("+")||s.contains("-")||s.contains("*")||s.contains("/")){ StringBuffer m=new StringBuffer(s); m.delete(m.length()-1, m.length()); } textField.setText("*"); k = 2; } }); panel_2.add(乘); JButton b0 = new JButton("0"); b0.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = new String(); s = textField.getText(); StringBuffer k = new StringBuffer(s); k.append("0"); String u = new String(k); textField.setText(u); } }); panel_2.add(b0); JButton 点 = new JButton("."); 点.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); panel_2.add(点); JButton 等 = new JButton("="); 等.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = textField.getText(); StringBuffer kBuffer=new StringBuffer(s); kBuffer.delete(0, 1); String uString =new String(kBuffer); y=Double.parseDouble(uString); if(k==0){ x = x + y; } if(k==1){ x = x-y; } if(k==2){ x = x*y; } if(k==3){ x = x/y; } String w = String.valueOf(x); textField.setText(w); x = 0; y = 0; } }); panel_2.add(等); JButton 除 = new JButton("/"); 除.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = textField.getText(); x=Double.parseDouble(s); if(s.contains("+")||s.contains("-")||s.contains("*")||s.contains("/")){ StringBuffer m=new StringBuffer(s); m.delete(m.length()-1, m.length()); } textField.setText("/"); k = 3; } }); panel_2.add(除); textField = new JTextField(); textField.setBounds(10, 0, 414, 50); contentPane.add(textField); textField.setColumns(10); } }
lxy15329 2012-11-27
  • 打赏
  • 举报
回复
今天看了设计模式,如果用简单工厂模式还是不错的
mxway 2012-11-27
  • 打赏
  • 举报
回复
这个是控制台的,实现四则运算,没有进行异常判断。
import java.util.ArrayList;
import java.util.Stack;
import java.util.StringTokenizer;
import java.io.*;

public class Main {
    public static void main(String []args)throws IOException{
        Stack<String> stack = new Stack<String>();
        ArrayList<String> list = new ArrayList<String>();
        BufferedReader buf = new BufferedReader(
                new InputStreamReader(System.in));
        String str = buf.readLine();
        while(!str.equals("0")){
            list.clear();
            stack.clear();
            StringTokenizer st = new StringTokenizer(str);
            while(st.hasMoreTokens()){
                String temp = st.nextToken();
                if(isOperation(temp)){
                    while(!stack.empty() && getPriority(temp)<=getPriority(stack.peek())){
                        list.add(stack.pop());
                    }
                    stack.push(temp);
                }else{
                    list.add(temp);
                }
            }
            while(!stack.empty()){
                list.add(stack.pop());
            }
            double num1 =0;
            double num2 = 0;
            for(int i=0;i<list.size();i++){
                if(isOperation(list.get(i))){
                    num2=Double.parseDouble(stack.pop());
                    num1=Double.parseDouble(stack.pop());
                    num1=cal(num1,num2,list.get(i));
                    stack.push(String.valueOf(num1));
                }else{
                    stack.push(list.get(i));
                }
            }
            System.out.println(String.format("%.2f",Double.valueOf(stack.pop())));
            str=buf.readLine();
        }
    }
    private static boolean isOperation(String op){
        if(op.equals("+") || op.equals("-")
                || op.equals("*") || op.equals("/")){
            return true;
        }
        return false;
    }
    private static int getPriority(String op){
        if(op.equals("+") || op.equals("-")){
            return 0;
        }else{
            return 1;
        }
    }
    private static double cal(double v1,double v2,String op){
        if(op.equals("+")){
            return v1+v2;
        }else if(op.equals("-")){
            return v1-v2;
        }else if(op.equals("*")){
            return v1*v2;
        }else{
            return v1/v2;
        }
    }
}
zqfddqr 2012-11-26
  • 打赏
  • 举报
回复
引用 4 楼 huntor 的回复:
输入一个合法的表达式,然后调用ScriptEngine来求值
这个风格我喜欢
duduyeye 2012-11-26
  • 打赏
  • 举报
回复
package test6;

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args){
    	boolean flag = true;

    	while(flag == true){
    		System.out.println("请输入任意两个数");
    		Scanner sc1 = new Scanner(System.in);
    		float a = sc1.nextFloat();
    		float b = sc1.nextFloat();
    		System.out.println("请输入选择:");
        	System.out.println("1.加法");
        	System.out.println("2.减法");
        	System.out.println("3.乘法");
        	System.out.println("4.除法");
        	System.out.println("5.求余");
        	System.out.println("0.退出");
    		System.out.print("请输入你的选择:");
    		Scanner sc = new Scanner(System.in);
    		int select  = sc.nextInt();
    		if((select < 0) || (select > 5)){
    			System.out.println("输入错误,请重新输入");
    			
    		}
    		switch(select){
    			case 0: System.exit(0);
    			case 1: Calculator.plus(a, b);
    			break;
    			case 2: Calculator.minus(a, b);
    			break;
    			case 3: Calculator.multiply(a, b);
    			break;
    			case 4: Calculator.divid(a, b);
    			break;
    			case 5: Calculator.remaind(a, b);
    			break;
    			default: break;
    		}
    		
    	}
	
    }
    public static  void plus(float a, float b){
		System.out.println("相加结果为:" + (a+b));
	}
    public static void minus(float a, float b){
    	System.out.println("相减结果为:" + (a-b));
    }
    public static void multiply(float a, float b){
    	System.out.println("相乘结果为:" + (a*b));
    	
    }
    public static void divid(float a, float b){
    	System.out.println("相除结果为:" + (a/b));
    }
    public static void remaind(float a, float b){
    	System.out.println("相除余数为:" + (a%b));
    }
}
  • 打赏
  • 举报
回复
引用 7 楼 zhaoming262350 的回复:
package com.test; import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.border.*; public class Calculator1 extends JFrame implements ActionListener { priv……
恩呢,正解啊
zhaoming262350 2012-11-24
  • 打赏
  • 举报
回复
package com.test; import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.border.*; public class Calculator1 extends JFrame implements ActionListener { private JFrame jf; private JButton[] allButtons; private JButton clearButton; private JButton sinButton; private JButton cosButton; private JButton tanButton; // private JButton cotButton; private JTextField jtf; private boolean isNew = true; private String recentOperation = null; private String recentNum = null; public Calculator1() { /** * 设置窗口点击关闭按钮能关闭 */ jf=new JFrame("计算器1.0:JAVA"); jf.addWindowListener(new WindowAdapter() { public void windowClosing(){ System.exit(0); } }); // 实例化所有的按钮以及编辑栏 allButtons = new JButton[16]; clearButton = new JButton("DEL"); sinButton = new JButton("sin"); cosButton = new JButton("cos"); tanButton = new JButton("tan"); jtf=new JTextField(25); jtf.setEditable(false); // jtf.setHorizontalAlignment(alignment) //给CanterPanel中的按钮添加标识符 String str="123+456-789*0.=/"; for(int i=0;i<allButtons.length;i++) { allButtons[i]=new JButton(str.substring(i,i+1)); } } public void init(){ //设置布局 jf.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 GridLayout(1,4)); northPanel.add(jtf); for(int i=0;i<16;i++){ centerPanel.add(allButtons[i]); } southPanel.add(sinButton); southPanel.add(cosButton); southPanel.add(tanButton); //southPanel.add(cotButton); southPanel.add(clearButton); jf.add(northPanel,BorderLayout.NORTH); jf.add(centerPanel,BorderLayout.CENTER); jf.add(southPanel,BorderLayout.SOUTH); addEventHandler(); } //添加事件监听 public void addEventHandler() { jtf.addActionListener(this); for(int i=0;i<allButtons.length;i++) { allButtons[i].addActionListener(this); } /** * 给DEL注册 */ clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub Calculator1.this.jtf.setText(""); } }); /*** * 实现sin,cos,tan 以及 allButton事件驱动按钮 */ sinButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double temp = Math.sin(Double.parseDouble(jtf.getText())); jtf.setText(String.valueOf(temp)); return; } }); cosButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double temp = Math.cos(Double.parseDouble(jtf.getText())); jtf.setText(String.valueOf(temp)); return; } }); tanButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double temp = Math.tan(Double.parseDouble(jtf.getText())); jtf.setText(String.valueOf(temp)); return; } }); /*cotButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double temp =- Double.parseDouble(jtf.getText()); jtf.setText(String.valueOf(temp)); return; } });*/ } //对输入数字的事件处理 public void actionPerformed(ActionEvent e) { String s= e.getActionCommand(); if(s.charAt(0)>='0'&&s.charAt(0)<='9') { if(!isNew) jtf.setText(jtf.getText()+s); else jtf.setText(s); isNew = false; } /** * 对“.”的事件处理 */ else if (s.equals(".")) { if(jtf.getText().indexOf(".")!=-1) return; if(!isNew &&jtf.getText()!="") jtf.setText(jtf.getText()+"."); else jtf.setText("0."); isNew = false; } //对"="的事件处理 else if(s.equals("=")) { equalaction(e); } else { if((jtf.getText()).equals("")) return; if(recentOperation !=null)equalaction(e); recentOperation = s; recentNum = jtf.getText(); isNew = true; } } /** * 对运算符及计算过程的事件处理 * @param e */ private void equalaction(ActionEvent e) { // TODO Auto-generated method stub if(recentOperation == null|| recentNum==null|| jtf.getText().equals("")) return; double last = 0,now = 0; try { last = Double.parseDouble(recentNum); now = Double.parseDouble(jtf.getText()); } catch(NumberFormatException en) { recentOperation = null; recentNum = null; jtf.setText("数据输入不合法"); System.out.println("数据输入不合法"); isNew = true; return; } if(recentOperation.equals("+")) { last+=now; } if(recentOperation.equals("-")) { last-=now; } if(recentOperation.equals("*")) { last*=now; } if(recentOperation.equals("/")) { last/=now; } jtf.setText(""+last); recentNum = jtf.getText(); recentOperation=null; isNew = true; } //对CenterPanel设置 public void setFontAndColor(){ Font f=new Font("宋体",Font.BOLD,24); jtf.setFont(f); jtf.setBackground(new Color(0x8f,0xa0,0xfb)); for(int i=0;i<16;i++) { allButtons[i].setFont(f); allButtons[i].setForeground(Color.RED); } } public void showMe(){ init(); setFontAndColor(); jf.pack(); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args){ new Calculator1().showMe(); } } /*** * 下面是第二个程序 * * */ /*************public class Calculator1 extends JFrame implements ActionListener { private boolean isNew = true; private String recentOperation = null; private String recentNum = null; private JPanel p1 = new JPanel(); private JPanel p2 = new JPanel(); private JTextField jtf = new JTextField(); private GridLayout gridLayout1 = new GridLayout() ; private GridBagLayout gridBagLayout1 = new GridBagLayout(); private GridBagLayout gridBagLayout2 = new GridBagLayout(); public void addButton(Container c,String s) { JButton b =new JButton(s); b.setFont(new java.awt.Font("SansSerif",0,12)); b.setForeground(Color.BLUE); b.setBorder(BorderFactory.createRaisedBevelBorder()); c.add(b); b.addActionListener( this); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String s= e.getActionCommand(); if(s.charAt(0)>='0'&&s.charAt(0)<='9') { if(!isNew) jtf.setText(jtf.getText()+s); else jtf.setText(s); isNew = false; } else if (s.equals(".")) { if(jtf.getText().indexOf(".")!=-1) return; if(!isNew &&jtf.getText()!="") jtf.setText(jtf.getText()+"."); else jtf.setText("0."); isNew = false; } else if(s.equals("=")) { equalaction(e); } else { if((jtf.getText()).equals("")) return; if(recentOperation !=null)equalaction(e); recentOperation = s; recentNum = jtf.getText(); isNew = true; } } private void equalaction(ActionEvent e) { // TODO Auto-generated method stub if(recentOperation == null|| recentNum==null|| jtf.getText().equals("")) return; double last = 0,now = 0; try { last = Double.parseDouble(recentNum); now = Double.parseDouble(jtf.getText()); } catch(NumberFormatException en) { recentOperation = null; recentNum = null; jtf.setText("数据输入不合法"); System.out.println("数据输入不合法"); isNew = true; return; } if(recentOperation.equals("+")) { last+=now; } if(recentOperation.equals("-")) { last-=now;
fish8245 2012-11-24
  • 打赏
  • 举报
回复
数据结构学堆栈时的一个经典例子,就是讲运算符优先级的!
Inhibitory 2012-11-24
  • 打赏
  • 举报
回复
要锻炼自己就去找本数据结构的书,看四则运算的实现,还可以使用逆波兰式实现,但是关键是要理解那个算符优先表
huntor 2012-11-24
  • 打赏
  • 举报
回复
输入一个合法的表达式,然后调用ScriptEngine来求值
青竹剑侠 2012-11-24
  • 打赏
  • 举报
回复
楼上正解,不过有点简单,不能实现连续运算和混合运算。
Jordan37 2012-11-24
  • 打赏
  • 举报
回复
下面是一个简单的程序:

import java.util.*; 
public class calc { 
public static void main(String[] args) { 
Scanner input = new Scanner(System.in); 
System.out.println("*****************简单计算器****************"); 
System.out.println("*\t\t\t\t\t*"); 
System.out.println("* 使用说明: 1.加法  2.减法  3.乘法  4.除法   * 5.退出"); 
System.out.println("*\t\t\t\t\t*"); 
System.out.println("*****************************************"); 

for(int i=0;i<100;i++){ 
System.out.print("\n请选择运算规则:"); 
int num = input.nextInt();
if (num == 5) {
	break;
}
switch(num){ 
case 1: 
System.out.println("\n******你选择了加法******\n"); 
System.out.print("请输入第1个加数:"); 
int jiashu1 = input.nextInt(); 
System.out.print("请输入第2个加数:"); 
int jiashu2 = input.nextInt(); 
System.out.println("运算结果为:" + jiashu1 + " + " + jiashu1 + " = " + (jiashu1 + jiashu2)); 
break; 
case 2: 
System.out.println("\n******你选择了减法******\n"); 
System.out.print("请输入被减数:"); 
int jianshu1 = input.nextInt(); 
System.out.print("请输入减数:"); 
int jianshu2 = input.nextInt(); 
System.out.println("运算结果为:" + jianshu1 + " - " + jianshu2 + " = " + (jianshu1 - jianshu2)); 
break; 
case 3: 
System.out.println("\n******你选择了乘法******\n"); 
System.out.print("请输入第1个因数:"); 
int chengfa1 = input.nextInt(); 
System.out.print("请输入第2个因数:"); 
int chengfa2 = input.nextInt(); 
System.out.println("运算结果为:" + chengfa1 + " * " + chengfa2 + " = " + (chengfa1 * chengfa2)); 
break; 
case 4: 
System.out.println("\n******你选择了除法******\n"); 
System.out.print("请输入被除数:"); 
double chufa1 = input.nextInt(); 
System.out.print("请输入除数:"); 
double chufa2 = input.nextInt(); 
System.out.println("运算结果为:" + chufa1 + " / " + chufa2 + " = " + (chufa1 / chufa2) + " 余 " + (chufa1 % chufa2)); 
break; 
default: 
System.out.println("\n你的选择有错,请重新选择!"); 
break; 
}
} 
} 
}
kenlee9033 2012-11-24
  • 打赏
  • 举报
回复
自己想想啊 又不难

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧