java计算器算法
Ⅰ java编写计算器
import java.awt.*;
public class CalcTest
{
public static void main(String args[])
{
Frame f=new Frame("计算器");
Panel P=new Panel();
P.setLayout(new GridLayout(4,4,1,1));
P.setSize(200,200);
TextField t=new TextField();
t.setBackground(Color.white);
t.setEnabled(false);
Button b0=new Button("0");
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
Button b6=new Button("6");
Button b7=new Button("7");
Button b8=new Button("8");
Button b9=new Button("9");
Button b10=new Button("+");
Button b11=new Button("-");
Button b12=new Button("*");
Button b13=new Button("/");
Button b14=new Button(".");
Button b15=new Button("=");
P.add(b1);
P.add(b2);
P.add(b3);
P.add(b10);
P.add(b4);
P.add(b5);
P.add(b6);
P.add(b11);
P.add(b7);
P.add(b8);
P.add(b9);
P.add(b12);
P.add(b0);
P.add(b14);
P.add(b15);
P.add(b13);
f.add(t,BorderLayout.NORTH);
f.add(P,BorderLayout.CENTER);
f.setResizable(false);
f.setSize(200,220);
f.setVisible(true);
}
}
希望可以帮到你,谢谢!
Ⅱ java设计个简单计算器
packagezhang16;
importjava.awt.*;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.text.DecimalFormat;
importjavax.swing.*;
importjavax.swing.border.Border;
importjavax.swing.border.LineBorder;
publicclass简单计算器16_4extendsJFrame{
privatedoublenum1,num2,res;
privateJTextFieldnumber1=newJTextField(5);
privateJTextFieldnumber2=newJTextField(5);
privateJTextFieldresult=newJTextField(10);
JButtonjia=newJButton("jia");
JButtonjian=newJButton("jian");
JButtoncheng=newJButton("cheng");
JButtonchu=newJButton("chu");
public简单计算器16_4(){
//TODOAuto-generatedconstructorstub
JPanelp1=newJPanel();
JPanelp2=newJPanel();
setLayout(newGridLayout(2,1));
this.add(p1,newFlowLayout());
p1.add(newJLabel("num1"));
p1.add(number1);
p1.add(newJLabel("num"));
p1.add(number2);
p1.add(newJLabel("result"));
p1.add(result);
Borderb=newLineBorder(Color.black,1);
this.add(p2,newFlowLayout());
p2.add(jia);
p2.add(jian);
p2.add(cheng);
p2.add(chu);
p1.setBorder(b);
p2.setBorder(b);
ButtonListenerActionListener=newButtonListener();
jia.addActionListener(ActionListener);
jian.addActionListener(ActionListener);
cheng.addActionListener(ActionListener);
chu.addActionListener(ActionListener);
}
{
@Override
publicvoidactionPerformed(ActionEvente){
//TODOAuto-generatedmethodstub
DecimalFormatdf=newDecimalFormat("0.00");
if(e.getSource()==jia){
Stringnum11=number1.getText();
num1=Double.parseDouble(num11);
Stringnum22=number2.getText();
num2=Double.parseDouble(num22);
res=num1+num2;
result.setText(df.format(res)+"");
}elseif(e.getSource()==jian){
Stringnum11=number1.getText();
num1=Double.parseDouble(num11);
Stringnum22=number2.getText();
num2=Double.parseDouble(num22);
res=num1-num2;
result.setText(df.format(res)+"");
}elseif(e.getSource()==cheng){
Stringnum11=number1.getText();
num1=Double.parseDouble(num11);
Stringnum22=number2.getText();
num2=Double.parseDouble(num22);
res=num1*num2;
result.setText(df.format(res)+"");
}elseif(e.getSource()==chu){
Stringnum11=number1.getText();
num1=Double.parseDouble(num11);
Stringnum22=number2.getText();
num2=Double.parseDouble(num22);
res=num1/num2;
result.setText(df.format(res)+"");
}
}
}
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
JFramef=new简单计算器16_4();
f.setSize(400,130);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
}
}
Ⅲ 怎么用java写一个gpa计算器
package vdb;
import java.util.Scanner;
public class GPACaculator {
public static void main(String[] args) {
String grade = "";
double credit1;
double credit2;
double credit3;
double credit4;
double gradeValue=0;
double totPtsClass1=0;
double totPtsClass2=0;
double totPtsClass3=0;
double totPtsClass4=0;
double totPts=0;
double totalCredits= 0;
double gpa;
Scanner console = new Scanner (System.in);
System.out.println("Please enter the number of credits of the class 1 (A number)");
credit1 = console.nextDouble();
System.out.println("Please enter your grades for the class 1(Capital letters such as A,B+, C-)");
grade = console.next();
if (grade.equals ("A"))
gradeValue= 4.00;
else if (grade.equals("A-"))
gradeValue= 3.67;
else if (grade.equals("B+"))
gradeValue = 3.33;
else if (grade.equals("B"))
gradeValue = 3.00;
else if (grade.equals ("B-"))
gradeValue = 2.67;
else if (grade.equals("C+"))
gradeValue = 2.33;
else if (grade.equals("C"))
gradeValue = 2.00;
else if (grade.equals ("D+"))
gradeValue = 1.33;
else if (grade.equals ("D"))
gradeValue = 1.00;
else if (grade.equals ("F"))
gradeValue = 0;
else if (grade.equals ("FX"))
gradeValue = 0;
else
System.out.println ("Invalid Grade");
totPtsClass1 = gradeValue * credit1;
System.out.println("Please enter the number of credits of the class 2 (A number)");
credit2 = console.nextDouble();
System.out.println("Please enter your grades for the class 2 (Capital letters such as A,B+, C-)");
grade = console.next();
if (grade.equals ("A"))
gradeValue= 4.00;
else if (grade.equals("A-"))
gradeValue= 3.67;
else if (grade.equals("B+"))
gradeValue = 3.33;
else if (grade.equals("B"))
gradeValue = 3.00;
else if (grade.equals ("B-"))
gradeValue = 2.67;
else if (grade.equals("C+"))
gradeValue = 2.33;
else if (grade.equals("C"))
gradeValue = 2.00;
else if (grade.equals ("D+"))
gradeValue = 1.33;
else if (grade.equals ("D"))
gradeValue = 1.00;
else if (grade.equals ("F"))
gradeValue = 0;
else if (grade.equals ("FX"))
gradeValue = 0;
else
System.out.println ("Invalid Grade");
totPtsClass2 = gradeValue * credit2;
System.out.println("Please enter the number of credits of the class 3 (A number)");
credit3 = console.nextDouble();
System.out.println("Please enter your grades for the class 3 (Capital letters such as A,B+, C-)");
grade = console.next();
if (grade.equals ("A"))
gradeValue= 4.00;
else if (grade.equals("A-"))
gradeValue= 3.67;
else if (grade.equals("B+"))
gradeValue = 3.33;
else if (grade.equals("B"))
gradeValue = 3.00;
else if (grade.equals ("B-"))
gradeValue = 2.67;
else if (grade.equals("C+"))
gradeValue = 2.33;
else if (grade.equals("C"))
gradeValue = 2.00;
else if (grade.equals ("D+"))
gradeValue = 1.33;
else if (grade.equals ("D"))
gradeValue = 1.00;
else if (grade.equals ("F"))
gradeValue = 0;
else if (grade.equals ("FX"))
gradeValue = 0;
else
System.out.println ("Invalid Grade");
totPtsClass3 = gradeValue * credit3;
System.out.println("Please enter the number of credits of the class 4 (A number)");
credit4 = console.nextDouble();
System.out.println("Please enter your grades for the class 4 (Capital letters such as A,B+, C-)");
grade = console.next();
if (grade.equals ("A"))
gradeValue= 4.00;
else if (grade.equals("A-"))
gradeValue= 3.67;
else if (grade.equals("B+"))
gradeValue = 3.33;
else if (grade.equals("B"))
gradeValue = 3.00;
else if (grade.equals ("B-"))
gradeValue = 2.67;
else if (grade.equals("C+"))
gradeValue = 2.33;
else if (grade.equals("C"))
gradeValue = 2.00;
else if (grade.equals ("D+"))
gradeValue = 1.33;
else if (grade.equals ("D"))
gradeValue = 1.00;
else if (grade.equals ("F"))
gradeValue = 0;
else if (grade.equals ("FX"))
gradeValue = 0;
else
System.out.println ("Invalid Grade");
totPtsClass4 = gradeValue * credit4;
totPts= totPtsClass1+totPtsClass2+totPtsClass3+totPtsClass4;
totalCredits = credit1+credit2+credit3+credit4;
gpa= totPts / totalCredits;
System.out.printf("Your GPA is: %.2f\n", new Object[] {gpa});
}
}
Ⅳ 谁知道用JAVA做计算器 运算怎么写的
给你一个我自己写的计算器参考!!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame{
private Container container;
private JTextField tf;
private Panel panel;
private String cmd;
private double result;
private boolean start;
Calculator(){
super("计算器");
container = getContentPane();
container.setLayout(new BorderLayout());
tf = new JTextField("0.0");
container.add(tf,BorderLayout.NORTH);
tf.setHorizontalAlignment(JTextField.RIGHT);
tf.setEditable(false);
panel = new Panel();
container.add(panel);
start = true;
result = 0;
cmd = "=";
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
addButton("1",insert);
addButton("2",insert);
addButton("3",insert);
addButton("0",insert);
addButton("*",command);
addButton("Back",insert);
addButton("4",insert);
addButton("5",insert);
addButton("6",insert);
addButton("+",command);
addButton("/",command);
addButton("Clear",insert);
addButton("7",insert);
addButton("8",insert);
addButton("9",insert);
addButton("-",command);
addButton(".",insert);
addButton("=",command);
setSize(400,200);
}
private void addButton(String str,ActionListener listener){
JButton button=new JButton(str);
button.addActionListener(listener);
panel.setLayout(new GridLayout(3,6));
panel.add(button);
}
private class InsertAction implements ActionListener{
public void actionPerformed(ActionEvent event){
String input=event.getActionCommand();
if (start)
{
tf.setText("");
start=false;
}
if(input.equals("Back"))
{
String str=tf.getText();
if(str.length()>0)
tf.setText(str.substring(0,str.length()-1));
}
else if(input.equals("Clear"))
{
tf.setText("0");
start=true;
}
else
tf.setText(tf.getText()+input);
}
}
private class CommandAction implements ActionListener{
public void actionPerformed(ActionEvent e){
String command=e.getActionCommand();
if(start)
{
cmd=command;
}
else
{
calculate(Double.parseDouble(tf.getText()));
cmd=command;
start=true;
}
}
}
public void calculate(double x){
if (cmd.equals("+")) result+=x;
else if (cmd.equals("-")) result-=x;
else if (cmd.equals("*")) result*=x;
else if (cmd.equals("/")) result/=x;
else if (cmd.equals("=")) result= x;
tf.setText(""+ result);
}
public static void main(String []args){
Calculator mycalculator=new Calculator();
mycalculator.setLocation(300,300);
mycalculator.setVisible(true);
}
}
Ⅳ 用Java编写一个简单的计算器程序
import java.awt.*;
import java.awt.event.*;
public class CalcAppDemo extends Frame{
private TextField t_result;
private Panel p_main; //主面板
private Panel p_num; //数字面板
private Panel p_oper; //操作符面板
private Panel p_show; //显示面板
private Button b_num[]; //数字按钮
private Button b_oper[]; //操作符面板
public CalcAppDemo(String title){
setTitle(title);
t_result = new TextField("0.0", 21);
p_main = new Panel();
p_num = new Panel();
p_oper = new Panel();
p_show = new Panel();
p_main.setLayout(new BorderLayout());
p_num.setLayout(new GridLayout(4, 3, 1, 1));
p_oper.setLayout(new GridLayout(4, 2, 1, 1));
b_num = new Button[12];
for(int i=0; i<9; i++)
{
b_num[i] = new Button(new Integer(i+1).toString());
}
b_num[9] = new Button("0");
b_num[10] = new Button("cls");
b_num[11] = new Button(".");
for(int i=0; i<12; i++)
{
p_num.add(b_num[i]);
}
b_oper = new Button[8];
b_oper[0] = new Button("+");
b_oper[1] = new Button("-");
b_oper[2] = new Button("*");
b_oper[3] = new Button("/");
b_oper[4] = new Button("pow");
b_oper[5] = new Button("sqrt");
b_oper[6] = new Button("+/-");
b_oper[7] = new Button("=");
for(int i=0; i<8; i++) //
{
p_oper.add(b_oper[i]);
}
t_result.setEditable(false);
p_show.add(t_result, BorderLayout.NORTH);
p_main.add(p_show, BorderLayout.NORTH);
p_main.add(p_num, BorderLayout.WEST);
p_main.add(p_oper, BorderLayout.EAST);
this.add(p_main, BorderLayout.CENTER);
setSize(400, 400);
setResizable(false);
pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
ButtonListener b1 = new ButtonListener();
for(int i=0; i<12; i++)
{
b_num[i].addActionListener(b1);
}
for(int i=0; i<8; i++)
{
b_oper[i].addActionListener(b1);
}
}
class ButtonListener implements ActionListener
{
private String lastOp; //存储上一此操作符
private String strVal; //存储数字对应的字符串
private double total; //总数
private double number; //存储新输入的数
private boolean firsttime; //判断是否第一次按下的是操作符按钮
private boolean operatorPressed;//判断是否已经按过操作符按钮
ButtonListener()
{
firsttime = true;
strVal = "";
}
//事件处理器
public void actionPerformed(ActionEvent e)
{
String s = ((Button)e.getSource()).getLabel().trim();
if(Character.isDigit(s.charAt(0)))
{//判断是操作数还是操作符
handleNumber(s);
}
else
{
calculate(s);
}
}
//判断是一元操作符还是二元操作符,并根据操作符类型做计算
void calculate(String op)
{
operatorPressed = true;
if(firsttime&&! isUnary(op))
{
total = getNumberOnDisplay();
firsttime = false;
}
if(isUnary(op))
{
handleUnaryOp(op);
}
else if(lastOp != null)
{
handleBinaryOp(lastOp);
}
if(! isUnary(op))
{
lastOp = op;
}
}
//判断是否一元操作符
boolean isUnary(String s)
{
return s.equals("=")
||s.equals("cls")||s.equals("sqrt")
||s.equals("+/-")||s.equals(".");
}
//处理一元操作符
void handleUnaryOp(String op)
{
if(op.equals("+/-"))
{//
number = negate(getNumberOnDisplay() + "");
t_result.setText("");
t_result.setText(number + "");
return;
}else if(op.equals("."))
{
handleDecPoint();
return;
}else if(op.equals("sqrt"))
{
number = Math.sqrt(getNumberOnDisplay());
t_result.setText("");
t_result.setText(number + "");
return;
}else if(op.equals("="))
{//
if(lastOp!= null && !isUnary(lastOp))
{
handleBinaryOp(lastOp);
}
lastOp = null;
firsttime = true;
return;
}else
{
clear();
}
}
//处理二元运算符
void handleBinaryOp(String op)
{
if(op.equals("+"))
{
total +=number;
}else if(op.equals("-"))
{
total -=number;
}else if(op.equals("*"))
{
total *=number;
}else if(op.equals("/"))
{
try
{
total /=number;
}catch(ArithmeticException ae){}
}else if(op.equals("pow"))
total = Math.pow(total, number);
//t_result.setText("");
lastOp = null;
// strVal = "";
number = 0;
t_result.setText(total + "");
}
//该方法用于处理数字按钮
void handleNumber(String s)
{
if(!operatorPressed)
{
strVal += s;
}else
{
operatorPressed = false;
strVal = s;
}
//
number = new Double(strVal).doubleValue();
t_result.setText("");
t_result.setText(strVal);
}
//该方法用于按下"."按钮
void handleDecPoint()
{
operatorPressed = false;
//
if(strVal.indexOf(".")<0)
{
strVal += ".";
}
t_result.setText("");
t_result.setText(strVal);
}
//该方法用于将一个数求反
double negate(String s)
{
operatorPressed = false;
//如果是一个整数,去掉小数点后面的0
if(number == (int)number)
{
s = s.substring(0,s.indexOf("."));
}
//如果无"-"增加在该数的前面
if(s.indexOf("-")<0)
{
strVal = "-" + s;
}
else
{
strVal = s.substring(1);
}
return new Double(strVal).doubleValue();
}
//将显示框中的值转换成Double
double getNumberOnDisplay()
{
return new Double(t_result.getText()).doubleValue();
}
//清除屏幕并设置所有的标识
void clear()
{
firsttime = true;
lastOp = null;
strVal = "";
total = 0;
number = 0;
t_result.setText("0");
}
}
public static void main(String[] args) {
CalcAppDemo c = new CalcAppDemo("简单的计算器程序");
c.setVisible(true);
}
}
Ⅵ 用java写计算器中两个大数作除法的思路算法是什么
BigDecimal类可以实现
import java.math.BigDecimal;
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1,double v2,int scale){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
Ⅶ JAVA 编写计算器 要代码最简单的
学java的时候自己编的,很简单,能够连续输入计算式后进行计算
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;
/**简易计算器,能够进行简单的计算
*
* @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="";//保存结果
StringBuilder sb = new StringBuilder();//保存要进行的计算式
int x = 0; //用来判断上一次的事件类型
String str = "123+456-789*0.=/";
ArrayList<String> arrayList = new ArrayList<String>();//保存计算式,通过方法进行运算
public CalculatorA(){
frame = new JFrame("我的计算器v1.1");
frame.setLocation(300,300);
field = new JTextField(25);
allButtons = new JButton[16];
for(int i=0;i<allButtons.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;i<allButtons.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);
}
//设置输入字体
public void setFondAndColor(){
field.setFont(new Font("宋体",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
field.setForeground(Color.RED);
//设置字体从右起始
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;i<allButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
// backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得当前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //当x为0时表示还没有进行输入
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("数据格式异常");
x = 0;
}
}
else if(x == 2){
field.setText("数据格式错误.....");
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("数据格式异常");
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 ArrayList<String> getResult(ArrayList<String> list){
String res = null;
String[] s = {"/","*","-","+"};
int i=0;
if(list.size()>1){
for(;i<s.length;){
if(s[i].equals("/")){
for(int j=0;j<list.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;j<list.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;j<list.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;j<list.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;
}
//对数字字符串进行排除不必要符号
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;k<c.length;k++){
c[k] = res.charAt(k);
}
for(int k=0;k<c.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();
}
}
Ⅷ java编程实现计算器
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Calculator extends Frame implements ActionListener {
private String s_show;
private String s_go;
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3=new Panel();
Oper do1 = new Oper();
TextField textfields = new TextField(27);
Dialog dlog=new Dialog(this,"about us");
Label aboutlab=new Label();
String s1;
String sedit;
Button buttons1 = new Button("Backspace");
int screenWidth,screenHeight;
Clipboard clp=Toolkit.getDefaultToolkit().getSystemClipboard();
Calculator() {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
MenuBar mbr=new MenuBar();
setMenuBar(mbr);
Menu edit=new Menu(" do ");
MenuItem =new MenuItem("Copy Ctrl+C");
MenuItem zhantie=new MenuItem(" Ctrl+V");
MenuItem exit=new MenuItem("Close Alt+F4");
edit.add();
edit.add(zhantie);
mbr.add(edit);
Menu help=new Menu(" help ");
MenuItem help1=new MenuItem("help theme");
MenuItem about=new MenuItem("about us");
dlog.setAlwaysOnTop(true);
dlog.setResizable(false);
//dlog.setEnabled(false);
s1="学习时兴趣小组做的";
aboutlab.setSize(200, 150);
aboutlab.setText(s1);
dlog.add(aboutlab);
about.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dlog.setVisible(true);
}
});
dlog.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dlog.setVisible(false);
}
});
help.add(help1);
help.add(about);
mbr.add(help);
p1.setBackground(Color.lightGray);
p1.setForeground(Color.red);
p2.setBackground(Color.lightGray);
p2.setForeground(Color.blue);
p1.setLayout(new FlowLayout(FlowLayout.RIGHT, 1,1));
p1.add(textfields);
p1.add(buttons1);
buttons1.addActionListener(this);
p2.setLayout(new GridLayout(5, 4, 10, 16));
this.add(p1, BorderLayout.CENTER);
this.add(p2, BorderLayout.SOUTH);
this.setTitle("Play the window");
this.setResizable(false);
this.setAlwaysOnTop(true);
/**textfields.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
char c=e.getKeyChar();
String textfieldsstr=textfields.toString();
switch(c){
case 1:textfields.setText(textfieldsstr+1);break;
case 2:textfields.setText(textfields.toString()+2);break;
case 3:textfields.setText(textfields.toString()+3);break;
case 4:textfields.setText(textfields.toString()+4);break;
case 5:textfields.setText(textfields.toString()+5);break;
case 6:textfields.setText(textfields.toString()+6);break;
case 7:textfields.setText(textfields.toString()+7);break;
case 8:textfields.setText(textfields.toString()+8);break;
case 9:textfields.setText(textfields.toString()+9);break;
case 0:textfields.setText(textfields.toString()+0);break;
case '*':textfields.setText(textfields.toString()+"*");break;
}
/**if(e.getKeyChar()==1){
textfields.setText(textfields.toString()+1);
}
}
});*///未实现键盘监听
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
screenWidth=screenSize.width;
screenHeight=screenSize.height;
this.setBounds(screenWidth/2-150, screenHeight/2-128, 300, 256);
dlog.setBounds(screenWidth/2-100, screenHeight/2-78, 200, 150);
int i, j = 0, k = 9, r1 = 0, r2 = 0, r3 = 0;
for (i = 0; i < 20; i++) {
j++;
if (j == 4) {
j = 0;
r1++;
Button buttons2_i = new Button();
p2.add(buttons2_i);
buttons2_i.setBackground(Color.cyan);
buttons2_i.addActionListener(this);
switch (r1) {
case 1:
buttons2_i.setLabel("+");
break;
case 2:
buttons2_i.setLabel("-");
break;
case 3:
buttons2_i.setLabel("*");
break;
case 4:
buttons2_i.setLabel("/");
break;
case 5:
buttons2_i.setLabel("=");
break;
}
}// endif
else // else1
{
if (i < 3) {
r2++;
Button buttons2_i = new Button(""); //
p2.add(buttons2_i);
buttons2_i.setBackground(Color.cyan);
buttons2_i.addActionListener(this);
switch (r2) {
case 1:
buttons2_i.setLabel("(");
break;
case 2:
buttons2_i.setLabel(")");
break;
case 3:
buttons2_i.setLabel("sqrt");
break;
}
}// endif
else {
if (i > 16 && i < 19) {
r3++;
Button buttons2_i = new Button("");
p2.add(buttons2_i);
buttons2_i.addActionListener(this);
switch (r3) {
case 1:
buttons2_i.setLabel(".");
break;
case 2:
buttons2_i.setLabel("CE");
break;
}
}// endif
else {
Integer name = new Integer(k);
k--;
s_show = name.toString();
Button buttons2_i = new Button(s_show);
p2.add(buttons2_i);
buttons2_i.addActionListener(this);
}
}
}// end else1
}// end for
s_show = "";
s_go = "";
this.setVisible(true);
}// end Calculator()构造方法
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) // if1
{
if (e.getActionCommand() == "CE")// Del
{
s_show = "";
s_go = "";
textfields.setText(s_show);
} else if (e.getActionCommand() == "Backspace") {
if (s_show.equals("")) {
s_go = "";
textfields.setText("");
} else {
if (s_go.length() > 0)
s_go = s_go.substring(0, s_go.length() - 1);
s_show = s_show.substring(0, s_show.length() - 1);
textfields.setText(s_show);
}
} else if (e.getActionCommand() == ".") {
if (textfields.getText().equals(""))
textfields.setText("0.");
else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
}
} else {
if (e.getActionCommand() != "=") {
if (e.getActionCommand().equals("sqrt")) {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
s_go = s_go.substring(0, s_go.length() - 3);
} else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(s_show);
}
} else {
s_show += e.getActionCommand();
s_go += e.getActionCommand();
textfields.setText(do1.operator(s_go)); // ().toString()
}
}// end else
}// end if1
if(e.getSource()==""){
sedit=textfields.getSelectedText();
StringSelection text=new StringSelection(sedit);
clp.setContents(text, null);
}
/**else if(e.getSource()=="zhantie"){
Transferable contents=clp.getContents(this);//返回表示剪贴板当前内容的 transferable 对象。
DataFlavor flavor=DataFlavor.stringFlavor;//
String ss;
if (contents.isDataFlavorSupported(flavor)) {
try
{
int start=textfields.getSelectionStart();
int end=textfields.getSelectionEnd();
//textfields.replaceRange("",start,end);
textfields.setText(ss);
ss = (String)contents.getTransferData(flavor);
int n=textfields.getCaretPosition();
textfields.insert(ss,n);
}catch(Exception ee){
// TODO: handle exception
}
}
}*///未实现剪贴板粘贴功能
// end actionPerformed()
// end class Calculator
}
public static void main(String args[]) {
Calculator cal = new Calculator();
}
}
Ⅸ 如何用java实现计算器运算功能用到哪些函数原代码怎么写呀
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Counter2 extends WindowAdapter
{
static JFrame f=new JFrame("¼ÆËãÆ÷");
static JTextField text1=new JTextField("0.");
static String source="";
static String cal="";
static String object="";
static boolean flag=false;
static boolean flag1=true;
static boolean flag2=false;
public void init()
{
try
{
Container c=f.getContentPane();
JPanel pan1=new JPanel();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
JButton b0=new JButton("0");
JButton b11=new JButton("+");
JButton b12=new JButton("-");
JButton b13=new JButton("*");
JButton b14=new JButton("/");
JButton b15=new JButton(".");
JButton b16=new JButton("=");
JButton bclar=new JButton("ÇåÁã");
text1.setHorizontalAlignment(JTextField.RIGHT);
c.add(text1,"North");
c.add(pan1);
A aa=new A();
Result re=new Result();
Opertion op=new Opertion();
Clar cl=new Clar();
b1.addActionListener(aa);
b2.addActionListener(aa);
b3.addActionListener(aa);
b4.addActionListener(aa);
b5.addActionListener(aa);
b6.addActionListener(aa);
b7.addActionListener(aa);
b8.addActionListener(aa);
b9.addActionListener(aa);
b0.addActionListener(aa);
b11.addActionListener(op);
b12.addActionListener(op);
b13.addActionListener(op);
b14.addActionListener(op);
b16.addActionListener(re);
b15.addActionListener(aa);
bclar.addActionListener(cl);
pan1.add(b1);
pan1.add(b2);
pan1.add(b3);
pan1.add(b11);
pan1.add(b4);
pan1.add(b5);
pan1.add(b6);
pan1.add(b12);
pan1.add(b7);
pan1.add(b8);
pan1.add(b9);
pan1.add(b13);
pan1.add(b0);
pan1.add(b15);
pan1.add(b16);
pan1.add(b14);
pan1.add(bclar);
f.setSize(200,220);
f.setVisible(true);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
class A implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String a=text1.getText();
String s=e.getActionCommand();
if(a.equals("0.")||a.equals("+")||a.equals("-")||a.equals("*")||a.equals("/"))
text1.setText(s);
else {
if(flag2)
{
text1.setText(s);
flag2=false;
}
else
text1.setText(a+s);
}
}
}
class Opertion implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
cal=e.getActionCommand();
if(flag1==true)
source=text1.getText();
text1.setText(cal);
flag1=false;
flag=true;
}
}
class Result implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double num1;
num1=Double.parseDouble(source);
object=text1.getText();
double num2;
num2=Double.parseDouble(object);
double result=0;
if(cal.equals("+"))
result=num1+num2;
if(cal.equals("-"))
result=num1-num2;
if(cal.equals("*"))
result=num1*num2;
if(cal.equals("/"))
if(num2==0)
text1.setText("³ýÊý²»ÄÜΪ0");
else
result=num1/num2;
String s1=Double.toString(result);
text1.setText(s1);
flag1=true;
flag2=true;
}
}
class Clar implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
text1.setText("0.");
}
}
public static void main(String[] args)
{
Counter2 count=new Counter2();
count.init();
}
public void windowClosing(WindowEvent e){
System.exit(1);
}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
}