『壹』 java如何实现3个 个位数的加减乘除运算
publicclassParamDemo{
publicstaticvoidmain(String[]args){
Map<String,Integer>map=newHashMap<>();
map.put("+",1);
map.put("-",1);
map.put("*",2);
map.put("/",2);
Scannerscanner=newScanner(System.in);
intnum1=scanner.nextInt();
intnum2=scanner.nextInt();
intnum3=scanner.nextInt();
Stringop1=scanner.next();
Stringop2=scanner.next();
//此时证明第一个操作符优先级大于第二个操作符
if(map.get(op1)-map.get(op2)>=0){
inttmpNumber=operateNum(op1,num1,num2);
System.out.println(operateNum(op2,tmpNumber,num3));
}else{
inttmpNumber=operateNum(op2,num2,num3);
System.out.println(operateNum(op1,num1,tmpNumber));
}
scanner.close();
}
privatestaticintoperateNum(Stringoperator,intnum1,intnum2){
switch(operator){
case"+":
returnnum1+num2;
case"-":
returnnum1-num2;
case"*":
returnnum1*num2;
case"/":
returnnum1/num2;
default:
return0;
}
}
}
『贰』 java中,用布局器实现计算器界面 并实现加减乘除等功能,怎样编程
java写的,可行
package ex1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextField;
public class Calcutor extends JFrame {
private JTextField tf;
private JPanel panel1, panel2, panel3, panel4;
private JMenuBar myBar;
private JMenu menu1, menu2, menu3;
private JMenuItem editItem1, editItem2, help1, help2, help3;
private JRadioButtonMenuItem seeItem1, seeItem2;//单选框
private JCheckBoxMenuItem seeItem3;//复选框
private ButtonGroup bgb;
private String back;
private boolean IfResult = true, flag = false;
private String oper = "=";
private double result = 0;
private Num numActionListener;
private DecimalFormat df;
public Calcutor(){
super("科学计算器");//设置标题栏
df = new DecimalFormat("#.####");//保留四位小数
this.setLayout(new BorderLayout(10, 5));
panel1 = new JPanel(new GridLayout(1, 3, 10, 10));
panel2 = new JPanel(new GridLayout(5, 6, 5, 5));//5行6列
panel3 = new JPanel(new GridLayout(5, 1, 5, 5));
panel4 = new JPanel(new BorderLayout(5, 5));
/**
* 菜单栏
*/
myBar = new JMenuBar();
menu1 = new JMenu("编辑(E)");
menu2 = new JMenu("查看(V)");
menu3 = new JMenu("帮助(H)");
menu1.setFont(new Font("宋体", Font.PLAIN, 12));
menu2.setFont(new Font("宋体", Font.PLAIN, 12));
menu3.setFont(new Font("宋体", Font.PLAIN, 12));
/**
* 编辑栏
*/
editItem1 = new JMenuItem("复制(C) Ctrl+C");
editItem2 = new JMenuItem("粘贴(P) Ctrl+V");
editItem1.setFont(new Font("宋体",Font.PLAIN,12));
editItem2.setFont(new Font("宋体",Font.PLAIN,12));
/**
* 查看栏
*/
seeItem1 = new JRadioButtonMenuItem("科学型(T)");
seeItem2 = new JRadioButtonMenuItem("标准型(S)");
seeItem3 = new JCheckBoxMenuItem("数字分组(I)");
seeItem1.setFont(new Font("宋体",Font.PLAIN,12));
seeItem2.setFont(new Font("宋体",Font.PLAIN,12));
seeItem3.setFont(new Font("宋体",Font.PLAIN,12));
/**
* 帮助栏
*/
help1 = new JMenuItem("帮助主题(H)");
help2 = new JMenuItem("关于计算器(A)");
help1.setFont(new Font("宋体",Font.PLAIN,12));
help2.setFont(new Font("宋体",Font.PLAIN,12));
bgb = new ButtonGroup();//选项组
menu1.add(editItem1);
menu1.add(editItem2);
menu2.add(seeItem1);
menu2.add(seeItem2);
menu2.addSeparator();//添加一条分割线
menu2.add(seeItem3);
menu3.add(help1);
menu3.addSeparator();//添加一条分割线
menu3.add(help2);
myBar.add(menu1);
myBar.add(menu2);
myBar.add(menu3);
this.setJMenuBar(myBar);
numActionListener = new Num();//实现数字监听
/**
* 文本域,即为计算器的屏幕显示区域
*/
tf = new JTextField();
tf.setEditable(false);//文本区域不可编辑
tf.setBackground(Color.white);//文本区域的背景色
tf.setHorizontalAlignment(JTextField.RIGHT);//文字右对齐
tf.setText("0");
tf.setBorder(BorderFactory.createLoweredBevelBorder());
init();//对计算器进行初始化
}
/**
* 初始化操作
* 添加按钮
*/
private void init(){
addButton(panel1, "Backspace", new Clear(), Color.red);
addButton(panel1, "CE", new Clear(), Color.red);
addButton(panel1, "C", new Clear(), Color.red);
addButton(panel2, "1/x", new Signs(), Color.magenta);
addButton(panel2, "log", new Signs(), Color.magenta);
addButton(panel2, "7", numActionListener, Color.blue);
addButton(panel2, "8", numActionListener, Color.blue);
addButton(panel2, "9", numActionListener, Color.blue);
addButton(panel2, "÷", new Signs(), Color.red);
addButton(panel2, "n!", new Signs(), Color.magenta);
addButton(panel2, "sqrt", new Signs(), Color.magenta);
addButton(panel2, "4", numActionListener, Color.blue);
addButton(panel2, "5", numActionListener, Color.blue);
addButton(panel2, "6", numActionListener, Color.blue);
addButton(panel2, "×", new Signs(), Color.red);
addButton(panel2, "sin", new Signs(), Color.magenta);
addButton(panel2, "x^2", new Signs(), Color.magenta);
addButton(panel2, "1", numActionListener, Color.blue);
addButton(panel2, "2", numActionListener, Color.blue);
addButton(panel2, "3", numActionListener, Color.blue);
addButton(panel2, "-", new Signs(), Color.red);
addButton(panel2, "cos", new Signs(), Color.magenta);
addButton(panel2, "x^3", new Signs(), Color.magenta);
addButton(panel2, "0", numActionListener, Color.blue);
addButton(panel2, "-/+", new Clear(), Color.blue);
addButton(panel2, ".", new Dot(), Color.blue);
addButton(panel2, "+", new Signs(), Color.red);
addButton(panel2, "tan", new Signs(), Color.magenta);
addButton(panel2, "%", new Signs(), Color.magenta);
addButton(panel2, "π", numActionListener, Color.orange);
addButton(panel2, "e", numActionListener, Color.orange);
addButton(panel2, "′″", new Signs(), Color.orange);
addButton(panel2, "=", new Signs(), Color.red);
JButton btns = new JButton("计算器");
btns.setBorder(BorderFactory.createLoweredBevelBorder());
btns.setEnabled(false);//按钮不可操作
btns.setPreferredSize(new Dimension(20, 20));
panel3.add(btns);//加入按钮
addButton(panel3, "MC", null, Color.red);
addButton(panel3, "MR", null, Color.red);
addButton(panel3, "MS", null, Color.red);
addButton(panel3, "M+", null, Color.red);
panel4.add(panel1, BorderLayout.NORTH);
panel4.add(panel2, BorderLayout.CENTER);
this.add(tf, BorderLayout.NORTH);
this.add(panel3, BorderLayout.WEST);
this.add(panel4);
pack();
this.setResizable(false);//窗口不可改变大小
this.setLocation(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* 统一设置按钮的的使用方式
* @param panel
* @param name
* @param action
* @param color
*/
private void addButton(JPanel panel, String name, ActionListener action, Color color){
JButton bt = new JButton(name);
panel.add(bt);//在面板上增加按钮
bt.setForeground(color);//设置前景(字体)颜色
bt.addActionListener(action);//增加监听事件
}
/**
* 计算器的基础操作(+ - × ÷)
* @param x
*/
private void getResult (double x){
if(oper == "+"){result += x;}
else if(oper == "-"){result -= x;}
else if(oper == "×"){result *= x;}
else if(oper == "÷"){result /= x;}
else if(oper == "="){result = x;}
tf.setText(df.format(result));
}
/**
* 运算符号的事件监听
*/
class Signs implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
* 用ActionEvent对象的getActionCommand()方法
* 取得与引发事件对象相关的字符串
*/
String str = e.getActionCommand();
/* sqrt求平方根 */
if(str.equals("sqrt")){
double i = Double.parseDouble(tf.getText());
if(i>=0){
/*
* String.valueOf() 转换为字符串
* df.format() 按要求保留四位小数
* Math.sqrt() 求算数平方根
*/
tf.setText(String.valueOf(df.format(Math.sqrt(i))));
}
else{
tf.setText("负数不能开平方根");
}
}
/* log求常用对数 */
else if(str.equals("log")){
double i = Double.parseDouble(tf.getText());
if(i>0){
tf.setText(String.valueOf(df.format(Math.log(i))));
}else{
tf.setText("负数不能求对数");
}
}
/* %求百分比 */
else if(str.equals("%")){
tf.setText(df.format(Double.parseDouble(tf.getText()) / 100));
}
/* 1/x求倒数 */
else if(str.equals("1/x")){
if(Double.parseDouble(tf.getText()) == 0){
tf.setText("除数不能为零");
}else{
tf.setText(df.format(1 / Double.parseDouble(tf.getText())));
}
}
/* sin求正弦函数 */
else if(str.equals("sin")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.sin(i))));
}
/* cos求余弦函数 */
else if(str.equals("cos")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.cos(i))));
}
/* tan求正切函数 */
else if(str.equals("tan")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.tan(i))));
}
/* n!求阶乘 */
else if(str.equals("n!")){
double i = Double.parseDouble(tf.getText());
if((i%2==0)||(i%2==1))//判断为整数放进行阶乘操作
{
int j = (int)i;//强制类型转换
int result=1;
for(int k=1;k<=j;k++)
result *= k;
tf.setText(String.valueOf(result));
}
else
{
tf.setText("无法进行阶乘");
}
}
/* x^2求平方 */
else if(str.equals("x^2")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i)));
}
/* x^3求立方 */
else if(str.equals("x^3")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i*i)));
}
/* ′″角度转换 */
/**
* 将角度值转换成弧度值,方便三角函数的计算
*/
else if(str.equals("′″")){
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(i/180*Math.PI));
}
else{
if(flag){
IfResult = false;
}
if(IfResult){
oper = str;
}else{
getResult(Double.parseDouble(tf.getText()));
oper = str;
IfResult = true;
}
}
}
}
/**
* 清除按钮的事件监听
*/
class Clear implements ActionListener{
public void actionPerformed(ActionEvent e) {
/*
* 用ActionEvent对象的getActionCommand()方法
* 取得与引发事件对象相关的字符串
*/
String str = e.getActionCommand();
if(str == "C"){
tf.setText("0");
IfResult = true;
result = 0;
}else if(str == "-/+"){
double i = 0 - Double.parseDouble(tf.getText().trim());
tf.setText(df.format(i));
}else if(str == "Backspace"){
if(Double.parseDouble(tf.getText()) > 0){
if(tf.getText().length() > 1){
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
//使用退格删除最后一位字符
}else{
tf.setText("0");
IfResult = true;
}
}else{
if(tf.getText().length() > 2){
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
}else{
tf.setText("0");
IfResult = true;
}
}
}else if(str == "CE"){
tf.setText("0");
IfResult = true;
}
}
}
/**
* 数字输入的事件监听
*/
class Num implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
if(IfResult){
tf.setText("");
IfResult = false;
}
if(str=="π")
{
tf.setText(String.valueOf(Math.PI));
}
else if(str=="e")
{
tf.setText(String.valueOf(Math.E));
}
else{
tf.setText(tf.getText().trim() + str);
if(tf.getText().equals("0")){
tf.setText("0");
IfResult = true;
flag = true;
}
}
}
}
/**
* 小数点的事件监听
*/
class Dot implements ActionListener{
public void actionPerformed(ActionEvent e) {
IfResult = false;
if(tf.getText().trim().indexOf(".") == -1){
tf.setText(tf.getText() + ".");
}
}
}
/**
* main方法
*/
public static void main(String[] args) {
new Calcutor().setVisible(true);
}
}
『叁』 加减乘除运算(Java)
实际上这相当于javascript的eval方法,以下是该方法的java实现:
//Eval.java
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Eval {
public int eval(String exp){
List<String> list = infixExpToPostExp(exp);//转化成后缀表达式
return doEval(list);//真正求值
}
//遇到操作符压栈,遇到表达式从后缀表达式中弹出两个数,计算出结果,压入堆栈
private int doEval(List<String> list) {
Stack<String> stack = new Stack<String>();
String element;
int n1,n2,result;
try{
for(int i = 0; i < list.size();i++){
element = list.get(i);
if(isOperator(element)){
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
result = doOperate(n1,n2,element);
stack.push(new Integer(result).toString());
}else{
stack.push(element);
}
}
return Integer.parseInt(stack.pop());
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
}
private int doOperate(int n1, int n2, String operator) {
if(operator.equals("+"))
return n1 + n2;
else if(operator.equals("-"))
return n1 - n2;
else if(operator.equals("*"))
return n1 * n2;
else
return n1 / n2;
}
private boolean isOperator(String str){
return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/");
}
private List<String> infixExpToPostExp(String exp){//将中缀表达式转化成为后缀表达式
List<String> postExp = new ArrayList<String>();//存放转化的后缀表达式的链表
StringBuffer numBuffer = new StringBuffer();//用来保存一个数的
Stack<Character> opStack = new Stack<Character>();//操作符栈
char ch,preChar;
opStack.push('#');
try{
for(int i = 0; i < exp.length();){
ch = exp.charAt(i);
switch(ch){
case '+':
case '-':
case '*':
case '/':
preChar = opStack.peek();
// 如果栈里面的操作符优先级比当前的大,则把栈中优先级大的都添加到后缀表达式列表中
while(priority(preChar) >= priority(ch)){
postExp.add(""+preChar);
opStack.pop();
preChar = opStack.peek();
}
opStack.push(ch);
i++;
break;
case '(':
// 左括号直接压栈
opStack.push(ch);
i++;
break;
case ')':
// 右括号则直接把栈中左括号前面的弹出,并加入后缀表达式链表中
char c = opStack.pop();
while(c != '('){
postExp.add("" + c);
c = opStack.pop();
}
i++;
break;
// #号,代表表达式结束,可以直接把操作符栈中剩余的操作符全部弹出,并加入后缀表达式链表中
case '#':
char c1;
while(!opStack.isEmpty()){
c1 = opStack.pop();
if(c1 != '#')
postExp.add("" + c1);
}
i++;
break;
//过滤空白符
case ' ':
case '\t':
i++;
break;
// 数字则凑成一个整数,加入后缀表达式链表中
default:
if(Character.isDigit(ch)){
while(Character.isDigit(ch)){
numBuffer.append(ch);
ch = exp.charAt(++i);
}
postExp.add(numBuffer.toString());
numBuffer = new StringBuffer();
}else{
throw new IllegalExpressionException("illegal operator");
}
}
}
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
return postExp;
}
private int priority(char op){//定义优先级
switch(op){
case'+':
case'-':
return 1;
case'*':
case'/':
return 2;
case'(':
case'#':
return 0;
}
throw new IllegalExpressionException("Illegal operator");
}
}
Main.java 主函数所在类
public class Main
{
public static void main(String[] args) {
try {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String exp=br.readLine();
int result = eval.eval(exp);
System.out.println(result);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
IllegalExpressionException异常类
public class IllegalExpressionException extends RuntimeException{
public IllegalExpressionException(){
}
public IllegalExpressionException(String info){
super(info);
}
}
『肆』 怎么用java编程,实现分数的加减乘除运算
package Rational;
import java.util.StringTokenizer;
/**
* @author SunKun
* 分数四则运算
*/
public class Calculator {
int numerator; // 分子
int denominator; // 分母
Calculator(){
}
Calculator(int a,int b){
if(a == 0){
numerator = 0;
denominator = 1;
}
else{
setNumeratorAndDenominator(a,b);
}
}
void setNumeratorAndDenominator(int a, int b){ // 设置分子和分母
int c = f(Math.abs(a),Math.abs(b)); // 计算最大公约数
numerator = a / c;
denominator = b / c;
if(numerator<0 && denominator<0){
numerator = - numerator;
denominator = - denominator;
}
}
int getNumerator(){
return numerator;
}
int getDenominator(){
return denominator;
}
int f(int a,int b){ // 求a和b的最大公约数
if(a < b){
int c = a;
a = b;
b = c;
}
int r = a % b;
while(r != 0){
a = b;
b = r;;
r = a % b;
}
return b;
}
Calculator add(Calculator r){ // 加法运算
int a = r.getNumerator();
int b = r.getDenominator();
int newNumerator = numerator * b + denominator * a;
int newDenominator = denominator * b;
Calculator result = new Calculator(newNumerator,newDenominator);
return result;
}
Calculator sub(Calculator r){ // 减法运算
int a = r.getNumerator();
int b = r.getDenominator();
int newNumerator = numerator * b - denominator * a;
int newDenominator = denominator * b;
Calculator result = new Calculator(newNumerator,newDenominator);
return result;
}
Calculator muti(Calculator r){ // 乘法运算
int a = r.getNumerator();
int b = r.getDenominator();
int newNumerator = numerator * a;
int newDenominator = denominator * b;
Calculator result = new Calculator(newNumerator,newDenominator);
return result;
}
Calculator div(Calculator r){ // 除法运算
int a = r.getNumerator();
int b = r.getDenominator();
int newNumerator = numerator * b;
int newDenominator = denominator * a;
Calculator result = new Calculator(newNumerator,newDenominator);
return result;
}
static Calculator qiuyu(double left,double right){ // 求余运算
double point_result = Math.IEEEremainder(left, right);
int r1 = (int)point_result;
double r2 = point_result - r1;
int newNumerator = r1*10000 + (int)(r2*10000);
int newDenominator = 10000;
Calculator result = new Calculator(newNumerator,newDenominator);
return result;
}
static Calculator pow(double left,double right){ // 求幂运算left^right
double point_result = Math.pow(left, right);
int r1 = (int)point_result;
double r2 = point_result - r1;
int newNumerator = r1*10000 + (int)(r2*10000);
int newDenominator = 10000;
Calculator result = new Calculator(newNumerator,newDenominator);
return result;
}
static Calculator max(double left,double right){ // 求两数中的较大值
double point_result = Math.min(left, right);
int r1 = (int)point_result;
double r2 = point_result - r1;
int newNumerator = r1*10000 + (int)(r2*10000);
int newDenominator = 10000;
Calculator result = new Calculator(newNumerator,newDenominator);
return result;
}
static Calculator min(double left,double right){ // 求两数中的较小值
double point_result = Math.min(left, right);
int r1 = (int)point_result;
double r2 = point_result - r1;
int newNumerator = r1*10000 + (int)(r2*10000);
int newDenominator = 10000;
Calculator result = new Calculator(newNumerator,newDenominator);
return result;
}
// 封装了具体运算,主要为对输入进行转换,对输出封装
public static void compute(String data1,String operation,String data2){
StringTokenizer fenxi = new StringTokenizer(data1,"/");
int data1_1 = Integer.parseInt(fenxi.nextToken());
int data1_2 = Integer.parseInt(fenxi.nextToken());
fenxi = new StringTokenizer(data2,"/");
int data2_1 = Integer.parseInt(fenxi.nextToken());
int data2_2 = Integer.parseInt(fenxi.nextToken());
Calculator r1 = new Calculator(data1_1,data1_2);
Calculator r2 = new Calculator(data2_1,data2_2);
Calculator result;
int a,b;
if(operation.equals("+")){ // 两数相加
result = r1.add(r2);
a = result.getNumerator();
b = result.getDenominator();
System.out.println(data1+" "+operation+" " +data2+" = " + a + "/" + b);
}
if(operation.equals("-")){ // 两数相减
result = r1.sub(r2);
a = result.getNumerator();
b = result.getDenominator();
System.out.println(data1+" "+operation+" " +data2+" = " + a + "/" + b);
}
if(operation.equals("*")){ // 两数相乘
result = r1.muti(r2);
a = result.getNumerator();
b = result.getDenominator();
System.out.println(data1+" "+operation+" " +data2+" = " + a + "/" + b);
}
if(operation.equals("/")){ // 两数相除
result = r1.div(r2);
a = result.getNumerator();
b = result.getDenominator();
System.out.println(data1+" "+operation+" " +data2+" = " + a + "/" + b);
}
if(operation.equals("%")){ // 两数求余
double left = (double)data1_1/(double)data1_2;
double right = (double)data2_1/(double)data2_2;
result = qiuyu(left,right);
a = result.getNumerator();
b = result.getDenominator();
System.out.println(data1+" "+operation+" " +data2+" = " + a + "/" + b);
}
if(operation.equals("^")){ // 两数求幂
double left = (double)data1_1/(double)data1_2;
double right = (double)data2_1/(double)data2_2;
result = pow(left,right);
a = result.getNumerator();
b = result.getDenominator();
System.out.println(data1+" "+operation+" " +data2+" = " + a + "/" + b);
}
if(operation.equals("max")){ // 两数中的较大值
double left = (double)data1_1/(double)data1_2;
double right = (double)data2_1/(double)data2_2;
result = max(left,right);
a = result.getNumerator();
b = result.getDenominator();
System.out.println(data1+" "+operation+" " +data2+" = " + a + "/" + b);
}
if(operation.equals("min")){ // 两数中的较小值
double left = (double)data1_1/(double)data1_2;
double right = (double)data2_1/(double)data2_2;
result = min(left,right);
a = result.getNumerator();
b = result.getDenominator();
System.out.println(data1+" "+operation+" " +data2+" = " + a + "/" + b);
}
}
}
『伍』 如何使用java实现加减乘除运算
java有内置的运算符
+ - * /
int a=1,b=2;
a+b;
a-b;
a*b;
a/b;
『陆』 JAVA制作一个简单的计算器。能实现两个数的加、减、乘、除四则运算
importjava.util.*;
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
importjava.applet.*;
{
booleani=true;
privateJButtonnum0=newJButton("0");
privateJButtonnum1=newJButton("1");
privateJButtonnum2=newJButton("2");
privateJButtonnum3=newJButton("3");
privateJButtonnum4=newJButton("4");
privateJButtonnum5=newJButton("5");
privateJButtonnum6=newJButton("6");
privateJButtonnum7=newJButton("7");
privateJButtonnum8=newJButton("8");
privateJButtonnum9=newJButton("9");
privateJButtonzuok=newJButton("(");
privateJButtonyouk=newJButton(")");
privateJButtondian=newJButton(".");
privateJButtonNULL=newJButton("N");
privateJButtonplu=newJButton("+");
privateJButtonmin=newJButton("-");
privateJButtonmul=newJButton("x");
privateJButtondiv=newJButton("/");
privateJButtonequ=newJButton("=");
privateJButtoncle=newJButton("C");//清除
privateJTextFieldspace=newJTextField(15);
publicvoidinit(){
JPaneltext=newJPanel();
text.setLayout(newFlowLayout());
text.add(space);
JPanelbuttons=newJPanel();
buttons.setLayout(newGridLayout(5,4));
buttons.add(num9);
buttons.add(num8);
buttons.add(num7);
buttons.add(plu);
buttons.add(num6);
buttons.add(num5);
buttons.add(num4);
buttons.add(min);
buttons.add(num3);
buttons.add(num2);
buttons.add(num1);
buttons.add(mul);
buttons.add(num0);
buttons.add(cle);
buttons.add(equ);
buttons.add(div);
(num9).addActionListener(this);
(num8).addActionListener(this);
(num7).addActionListener(this);
(num6).addActionListener(this);
(num5).addActionListener(this);
(num4).addActionListener(this);
(num3).addActionListener(this);
(num2).addActionListener(this);
(num1).addActionListener(this);
(num0).addActionListener(this);
(plu).addActionListener(this);
(min).addActionListener(this);
(mul).addActionListener(this);
(div).addActionListener(this);
(equ).addActionListener(this);
(cle).addActionListener(this);
setLayout(newBorderLayout());
add("North",text);
add("South",buttons);
space.setText("0");
}
publicvoidactionPerformed(ActionEvente){
if(e.getSource()==num9){
if(i==true){
space.setText("9");
i=false;
}else
space.setText(space.getText()+'9');
}
if(e.getSource()==num8){
if(i==true){
space.setText("8");
i=false;
}else
space.setText(space.getText()+'8');
}
if(e.getSource()==num7){
if(i==true){
space.setText("7");
i=false;
}else
space.setText(space.getText()+'7');
}
if(e.getSource()==num6){
if(i==true){
space.setText("6");
i=false;
}else
space.setText(space.getText()+'6');
}
if(e.getSource()==num5){
if(i==true){
space.setText("5");
i=false;
}else
space.setText(space.getText()+'5');
}
if(e.getSource()==num4){
if(i==true){
space.setText("4");
i=false;
}else
space.setText(space.getText()+'4');
}
if(e.getSource()==num3){
if(i==true){
space.setText("3");
i=false;
}else
space.setText(space.getText()+'3');
}
if(e.getSource()==num2){
if(i==true){
space.setText("2");
i=false;
}else
space.setText(space.getText()+'2');
}
if(e.getSource()==num1){
if(i==true){
space.setText("1");
i=false;
}else
space.setText(space.getText()+'1');
}
if(e.getSource()==num0){
if(i==true){
space.setText("0");
i=false;
}else
space.setText(space.getText()+'0');
}
if(e.getSource()==plu){
space.setText(space.getText()+'+');
i=false;
}
if(e.getSource()==min){
space.setText(space.getText()+'-');
i=false;
}
if(e.getSource()==mul){
space.setText(space.getText()+'*');
i=false;
}
if(e.getSource()==div){
space.setText(space.getText()+'/');
i=false;
}
if(e.getSource()==equ){
space.setText(String.valueOf(Calculator(space.getText())));
i=true;
}
if(e.getSource()==cle){
space.setText("0");
i=true;
}
}
publicdoubleCalculator(Stringf)//科学计算
{
inti=0,j=0,k;
charc;
StringBuffers=newStringBuffer();
s.append(f);
s.append('=');
Stringformula=s.toString();
char[]anArray;
anArray=newchar[50];
Stack<Character>mystack=newStack<Character>();
while(formula.charAt(i)!='='){
c=formula.charAt(i);
switch(c){
case'+':
case'-':
while(!mystack.empty()&&mystack.peek().charValue()!='('){
anArray[j++]=mystack.pop().charValue();
}
mystack.push(newCharacter(c));
i++;
break;
case'*':
case'/':
while(!mystack.empty()
&&(mystack.peek().charValue()=='*'||mystack.peek()
.charValue()=='/')){
anArray[j++]=mystack.pop().charValue();
}
mystack.push(newCharacter(c));
i++;
break;
case'':
i++;
break;
default:
while((c>='0'&&c<='9')||c=='.'){
anArray[j++]=c;
i++;
c=formula.charAt(i);
}
anArray[j++]='#';
break;
}
}
while(!(mystack.empty()))
anArray[j++]=mystack.pop().charValue();
i=0;
intcount;
doublea,b,d;
Stack<Double>mystack1=newStack<Double>();
while(i<j){
c=anArray[i];
switch(c){
case'+':
a=mystack1.pop().doubleValue();
b=mystack1.pop().doubleValue();
d=b+a;
mystack1.push(newDouble(d));
i++;
break;
case'-':
a=mystack1.pop().doubleValue();
b=mystack1.pop().doubleValue();
d=b-a;
mystack1.push(newDouble(d));
i++;
break;
case'*':
a=mystack1.pop().doubleValue();
b=mystack1.pop().doubleValue();
d=b*a;
mystack1.push(newDouble(d));
i++;
break;
case'/':
a=mystack1.pop().doubleValue();
b=mystack1.pop().doubleValue();
if(a!=0){
d=b/a;
mystack1.push(newDouble(d));
i++;
}else{
System.out.println("Error!");
}
break;
default:
d=0;
count=0;
while((c>='0'&&c<='9')){
d=10*d+c-'0';
i++;
c=anArray[i];
}
if(c=='.'){
i++;
c=anArray[i];
while((c>='0'&&c<='9')){
count++;
d=d+(c-'0')/Math.pow(10,count);
i++;
c=anArray[i];
}
}
if(c=='#')
mystack1.push(newDouble(d));
i++;
break;
}
}
return(mystack1.peek().doubleValue());
}
}
你看看这个合适不?