導航:首頁 > 編程語言 > java中實現加減乘除的方法

java中實現加減乘除的方法

發布時間:2023-10-18 06:59:52

『壹』 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());
}
}

你看看這個合適不?

閱讀全文

與java中實現加減乘除的方法相關的資料

熱點內容
分布式服務如何跨庫統計數據 瀏覽:829
力控轉發數據客戶端模式如何建立 瀏覽:200
怎麼樣讓自己的網站不被別人看到 瀏覽:711
編程擴展效果如何 瀏覽:335
榮耀暢玩手環同步qq 瀏覽:475
怎麼向sql中添加資料庫 瀏覽:596
錄歌失敗重啟app什麼意思 瀏覽:522
壓縮文件包怎麼在微信發送 瀏覽:432
mysql資料庫怎麼插入時間值 瀏覽:191
微信視頻不能轉發朋友圈 瀏覽:596
影視後期的app有哪些 瀏覽:956
電子保單數據出錯什麼意思 瀏覽:368
如何以文件下載音樂 瀏覽:438
計算機網路章節練習 瀏覽:999
單片機的外部中斷程序 瀏覽:48
表格批量更名找不到指定文件 瀏覽:869
js的elseif 瀏覽:584
3dmaxvray視頻教程 瀏覽:905
imgtool工具中文版 瀏覽:539
java幫助文件在哪裡 瀏覽:965

友情鏈接