导航:首页 > 编程语言 > java设计简易计算器

java设计简易计算器

发布时间:2024-08-11 14:25:42

① 编写java程序简单计算器

主要涉及的知识点: 类的写法, 以及方法的调用 .建议多做练习. 如果有看不懂的地方. 可以继续追问,一起讨论.

参考代码如下

//Number类
classNumber{

privateintn1;//私有的整型数据成员n1
privateintn2;//私有的整型数据成员n2

//通过构造函数给n1和n2赋值
publicNumber(intn1,intn2){
this.n1=n1;
this.n2=n2;
}

//加法
publicintaddition(){
returnn1+n2;
}

//减法
publicintsubtration(){
returnn1-n2;
}

//乘法
publicintmultiplication(){
returnn1*n2;
}

//除法(可能除不尽,所以使用double作为返回类型)
publicdoubledivision(){
returnn1*1.0/n2;//通过n1*1.0把计算结果转换成double类型.
}
}

//Exam4类
publicclassExam4{
publicstaticvoidmain(String[]args){
Numbernumber=newNumber(15,6);//创建Number类的对象
//下面的是调用方法得到返回值进行输出显示
System.out.println("加法"+number.addition());
System.out.println("减法"+number.subtration());
System.out.println("乘法"+number.multiplication());
System.out.println("除法"+number.division());

}
}

② JAVA在WEB上的应用——实现简易计算器

建立14个按钮,按钮的名字都要Command1,设置Index属性,0~9分别对应数字0~9,10为小数点,11为等号,12~14分别对应+、-、*和/。
2、输入如下代码:
Dim Num1, Num2 As Single
Dim StrNum1, StrNum2 As String
Dim FirstNum As Boolean
Dim PointFlag As Boolean
Dim Runsign As Integer
Dim SignFlag As Boolean
Private Sub Command1_Click(Index As Integer)
Select Case Index
Case 0 To 9
If FirstNum Then
StrNum1 = Str(Index)
FirstNum = False
Else
StrNum1 = LTrim(StrNum1) + LTrim(Str(Index))
End If
Text1.Text = Val(StrNum1)
Case 10
If Not PointFlag Then
If FirstNum Then
StrNum1 = "0."
FirstNum = False
Else
StrNum1 = LTrim(StrNum1) + LTrim(".")
End If
Else
Exit Sub
End If
PointFlag = True
Text1.Text = Val(StrNum1)
Case 12 To 15
FirstNum = True
PointFlag = False
If SignFlag Then
Call Run
Else
SignFlag = True
StrNum2 = StrNum1
StrNum1 = ""
End If
Runsign = Index - 11
Case 11
On Error Resume Next
If Not SignFlag Then
Text1.Text = StrNum1
equal = Val(StrNum1)
FirstNum = True
PointFlag = False
Else
Call Run
SignFlag = False
End If
Case Else
Call ClearData
End Select
End Sub
Private Sub Form_Load()
If App.PrevInstance Then MsgBox "请不要多次运行此程序,谢谢!", vbAbortRetryIgnore: Unload Me
Num1 = 0
Num2 = 0
StrNum1 = ""
StrNum2 = ""
FirstNum = True
PointFlag = False
Runsign = 0
SignFlag = False
End Sub
Sub Run()
On Error Resume Next
Dim equal As Single
Dim equal2 As Double
Num1 = Val(StrNum2)
Num2 = Val(StrNum1)
Select Case Runsign
Case 1
equal = Num1 + Num2
If Num1 >= 65536 Or Num2 >= 65536 Or equal >= 65536 Then
equal = 0
equal2 = Num1 + Num2
End If
Case 2
equal = Num1 - Num2
If Num1 >= 65536 Or Num2 >= 65536 Or equal >= 65536 Then
equal = 0
equal2 = Num1 - Num2
End If
Case 3
equal = Num1 * Num2
If Num1 >= 65536 Or Num2 >= 65536 Or equal >= 65536 Then
equal = 0
equal2 = Num1 * Num2
End If
Case 4
equal = Num1 / Num2
If Num1 >= 65536 Or Num2 >= 65536 Or equal >= 65536 Then
equal = 0
equal2 = Num1 / Num2
End If
End Select
If equal = 0 Then a = equal2 Else a = equal
StrNum2 = Str(a)
StrNum1 = StrNum2
Text1.Text = Val(StrNum2)
End Sub
Sub ClearData()
Num1 = 0
Num2 = 0
StrNum1 = ""
StrNum2 = ""
FirstNum = True
PointFlag = False
Runsign = 0
SignFlag = False
Text1.Text = 0
End Sub

③ 怎么做一个JAVA计算器

classCalcBtnextendsJButton{

=1L;

Fontfont=newFont("仿宋",1,22);

publicCalcBtn(Stringtext,Colorcolor){

super(text);

setForeground(color);

setFont(font);

setMargin(newInsets(0,0,0,0));

setFocusable(false);

}

}

@SuppressWarnings("serial")

{

publicstaticvoidmain(String[]args){

try{

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

}catch(Exceptionex){

ex.printStackTrace();

}

newCalcFrame().setVisible(true);

}

privateCalcBtnbtn_1=newCalcBtn("1",Color.BLUE);

privateCalcBtnbtn_2=newCalcBtn("2",Color.BLUE);

privateCalcBtnbtn_3=newCalcBtn("3",Color.BLUE);

privateCalcBtnbtn_4=newCalcBtn("4",Color.BLUE);

privateCalcBtnbtn_5=newCalcBtn("5",Color.BLUE);

privateCalcBtnbtn_6=newCalcBtn("6",Color.BLUE);

privateCalcBtnbtn_7=newCalcBtn("7",Color.BLUE);

privateCalcBtnbtn_8=newCalcBtn("8",Color.BLUE);

privateCalcBtnbtn_9=newCalcBtn("9",Color.BLUE);

privateCalcBtnbtn_0=newCalcBtn("0",Color.BLUE);

privateCalcBtnbtn_back=newCalcBtn("←",Color.red);

privateCalcBtnbtn_c=newCalcBtn("C",Color.red);

privateCalcBtnbtn_ce=newCalcBtn("CE",Color.red);

privateCalcBtnbtn_sub=newCalcBtn("-",Color.red);

privateCalcBtnbtn_multi=newCalcBtn("*",Color.red);

privateCalcBtnbtn_div=newCalcBtn("/",Color.red);

privateCalcBtnbtn_add=newCalcBtn("+",Color.red);

privateCalcBtnbtn_sqrt=newCalcBtn("sqrt",Color.BLUE);

privateCalcBtnbtn_mod=newCalcBtn("%",Color.BLUE);

privateCalcBtnbtn_x=newCalcBtn("1/x",Color.BLUE);

privateCalcBtnbtn_res=newCalcBtn("=",Color.red);

privateCalcBtnbtn_point=newCalcBtn(".",Color.red);

privateCalcBtnbtn_flag=newCalcBtn("+/-",Color.BLUE);

privateJButtonbtn_mem=newJButton("");

privateCalcBtnbtn_m=newCalcBtn("M+",Color.BLUE);

privateCalcBtnbtn_mc=newCalcBtn("MC",Color.BLUE);

privateCalcBtnbtn_mr=newCalcBtn("MR",Color.BLUE);

privateCalcBtnbtn_ms=newCalcBtn("MS",Color.BLUE);

JPanelpan_jtf=newJPanel();

JPanelpan_back=newJPanel();

JPanelpan_mem=newJPanel();

JPanelpan_num=newJPanel();

JTextFieldjtf_res=newJTextField();

//

privateJMenuBarmenuBar=newJMenuBar();

privateJMenumenu_edit=newJMenu("编辑(E)");

privateJMenumenu_view=newJMenu("查看(V)");

privateJMenumenu_help=newJMenu("帮助(H)");

privateJMenuItemeditMenu_=newJMenuItem("复制(C)");

privateJMenuItemeditMenu_paste=newJMenuItem("粘贴(P)");

_standard=newJCheckBoxMenuItem(

"标准型(T)");

_science=newJCheckBoxMenuItem("科学型(S)");

_grouping=newJCheckBoxMenuItem(

"数字分组(I)");

privateJMenuItemhelpmenu_help=newJMenuItem("帮助主题(H)");

privateJMenuItemhelpmenu_about=newJMenuItem("关于计算器(A)");

Stringsave1,save2;

BigDecimalop1,op2;

booleanisBigDecimal=false;

intpreOp,currentOp=0;

StringBufferstr=newStringBuffer();

publicCalcFrame(){

this.setTitle("于☆弦");

this.setResizable(false);

setSize(444,390);

setLocationRelativeTo(null);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setJMenuBar(menuBar);

setLayout(null);

init_pan_jtf();

init_menuBar();

init_pan_back();

init_pan_mem();

init_pan_num();

getContentPane().add(pan_jtf);

getContentPane().add(pan_back);

getContentPane().add(pan_mem);

getContentPane().add(pan_num);

}

privatevoidinit_menuBar(){

menuBar.add(menu_edit);

menuBar.add(menu_view);

menuBar.add(menu_help);

menu_edit.add(editMenu_);

menu_edit.add(editMenu_paste);

menu_view.add(viewmenu_standard);

menu_view.add(viewmenu_science);

menu_view.addSeparator();

menu_view.add(viewmenu_grouping);

menu_help.add(helpmenu_help);

menu_help.addSeparator();

menu_help.add(helpmenu_about);

menu_edit.setMnemonic('E');

menu_view.setMnemonic('V');

menu_help.setMnemonic('H');

editMenu_.setMnemonic('C');

editMenu_.setAccelerator(KeyStroke.getKeyStroke('C',

InputEvent.CTRL_MASK));

editMenu_paste.setMnemonic('P');

editMenu_paste.setAccelerator(KeyStroke.getKeyStroke('V',

InputEvent.CTRL_MASK));

viewmenu_standard.setMnemonic('T');

viewmenu_science.setMnemonic('S');

viewmenu_grouping.setMnemonic('I');

helpmenu_help.setMnemonic('H');

helpmenu_about.setMnemonic('A');

}

publicvoidinit_pan_back(){

pan_back.setSize(340,40);

pan_back.setLocation(85,60);

pan_back.setLayout(newGridLayout(1,3,5,0));

pan_back.add(btn_back);

pan_back.add(btn_ce);

pan_back.add(btn_c);

btn_back.addActionListener(newActionListener(){

publicvoidactionPerformed(ActionEvente){

if(!jtf_res.getText().trim().equals("0.")){

if(str.length()!=1&&str.length()!=0){

jtf_res.setText(str.delete(str.length()-1,

str.length()).toString());

}else{

jtf_res.setText("0.");

str.setLength(0);

}

}

op2=newBigDecimal(jtf_res.getText().trim());

}

});

btn_c.addActionListener(newActionListener(){

publicvoidactionPerformed(ActionEvente){

jtf_res.setText("0.");

op1=op2=newBigDecimal(0);

str.replace(0,str.length(),"");

preOp=currentOp=0;

}

});

btn_ce.addActionListener(newActionListener(){

publicvoidactionPerformed(ActionEvente){

jtf_res.setText("0.");

}

});

}

publicvoidinit_pan_jtf(){

jtf_res.setHorizontalAlignment(JTextField.RIGHT);

jtf_res.setFont(newFont("仿宋",0,20));

jtf_res.setText("0.");

jtf_res.setEditable(false);

//jtf_res.setFocusable(false);

pan_jtf.setSize(420,40);

pan_jtf.setLocation(10,5);

pan_jtf.setLayout(newBorderLayout());

pan_jtf.add(jtf_res);

}

publicvoidinit_pan_mem(){

pan_mem.setSize(60,270);

pan_mem.setLocation(10,60);

pan_mem.setLayout(newGridLayout(5,1,0,5));

pan_mem.add(btn_mem);

btn_mem.setEnabled(false);

pan_mem.add(btn_mc);

pan_mem.add(btn_mr);

pan_mem.add(btn_ms);

pan_mem.add(btn_m);

}

publicvoidinit_pan_num(){

pan_num.setSize(340,220);

pan_num.setLocation(85,110);

pan_num.setLayout(newGridLayout(4,5,5,5));

pan_num.add(btn_7);

pan_num.add(btn_8);

pan_num.add(btn_9);

pan_num.add(btn_div);

pan_num.add(btn_sqrt);

pan_num.add(btn_4);

pan_num.add(btn_5);

pan_num.add(btn_6);

pan_num.add(btn_multi);

pan_num.add(btn_mod);

pan_num.add(btn_1);

pan_num.add(btn_2);

pan_num.add(btn_3);

pan_num.add(btn_sub);

pan_num.add(btn_x);

pan_num.add(btn_0);

pan_num.add(btn_flag);

pan_num.add(btn_point);

pan_num.add(btn_add);

pan_num.add(btn_res);

btn_1.addActionListener(this);

btn_2.addActionListener(this);

btn_3.addActionListener(this);

btn_4.addActionListener(this);

btn_5.addActionListener(this);

btn_6.addActionListener(this);

btn_7.addActionListener(this);

btn_8.addActionListener(this);

btn_9.addActionListener(this);

btn_0.addActionListener(this);

btn_sub.addActionListener(this);

btn_multi.addActionListener(this);

btn_div.addActionListener(this);

btn_add.addActionListener(this);

btn_sqrt.addActionListener(this);

btn_x.addActionListener(this);

btn_res.addActionListener(this);

btn_point.addActionListener(this);

btn_flag.addActionListener(this);

//btn_mod.addActionListener(this);

}

@Override

publicvoidactionPerformed(ActionEvente){

Strings=e.getActionCommand();

BigDecimali=newBigDecimal(1);

Stringtemp=jtf_res.getText().trim();

BigDecimaltemp1=newBigDecimal(temp);

if(e.getSource()==btn_flag){

BigDecimaltemp3=newBigDecimal(jtf_res.getText());

BigDecimaltemp4=newBigDecimal(-1);

BigDecimaltemp5=temp3.multiply(temp4);

jtf_res.setText(""+temp5);

}elseif(s.equals("1/x")){

jtf_res.setText(""+i.divide(temp1,newMathContext(30)));

}elseif(s.equals("sqrt")){

jtf_res.setText(""+temp1.multiply(temp1));

}elseif(s.equals("+")){

str.setLength(0);

if(currentOp==0){

preOp=currentOp=1;

op2=newBigDecimal("0");

jtf_res.setText(""+op1);

}else{

currentOp=preOp;

preOp=1;

switch(currentOp){

case1:

op1=op1.add(op2);

jtf_res.setText(""+op1);

break;

case2:

op1=op1.subtract(op2);

jtf_res.setText(""+op1);

break;

case3:

op1=op1.multiply(op2);

jtf_res.setText(""+op1);

break;

case4:

op1=op1.divide(op2,newMathContext(30));

jtf_res.setText(""+op1);

break;

}

}

}elseif(s.equals("-")){

str.setLength(0);

if(currentOp==0){

preOp=currentOp=2;

jtf_res.setText(""+op1);

}else{

currentOp=preOp;

preOp=2;

switch(currentOp){

case1:

op1=op1.add(op2);

jtf_res.setText(""+op1);

break;

case2:

op1=op1.subtract(op2);

jtf_res.setText(""+op1);

break;

case3:

op1=op1.multiply(op2);

jtf_res.setText(""+op1);

break;

case4:

op1=op1.divide(op2,newMathContext(30));

jtf_res.setText(""+op1);

break;

}

}

}elseif(s.equals("*")){

str.setLength(0);

if(currentOp==0){

preOp=currentOp=3;

jtf_res.setText(""+op1);

}else{

currentOp=preOp;

preOp=3;

switch(currentOp){

case1:

op1=op1.add(op2);

jtf_res.setText(""+op1);

break;

case2:

op1=op1.subtract(op2);

jtf_res.setText(""+op1);

break;

case3:

op1=op1.multiply(op2);

jtf_res.setText(""+op1);

break;

case4:

op1=op1.divide(op2,newMathContext(30));

jtf_res.setText(""+op1);

break;

}

}

}elseif(s.equals("/")){

str.setLength(0);

if(currentOp==0){

preOp=currentOp=4;

jtf_res.setText(""+op1);

}else{

currentOp=preOp;

preOp=4;

switch(currentOp){

case1:

op1=op1.add(op2);

jtf_res.setText(""+op1);

break;

case2:

op1=op1.subtract(op2);

jtf_res.setText(""+op1);

break;

case3:

op1=op1.multiply(op2);

jtf_res.setText(""+op1);

break;

case4:

op1=op1.divide(op2,newMathContext(30));

jtf_res.setText(""+op1);

break;

}

}

}elseif(s.equals("=")){

if(currentOp==0){

str.setLength(0);

jtf_res.setText(""+op2);

}else{

str.setLength(0);

currentOp=preOp;

switch(currentOp){

case1:

op1=op1.add(op2);

jtf_res.setText(""+op1);

break;

case2:

op1=op1.subtract(op2);

jtf_res.setText(""+op1);

break;

case3:

op1=op1.multiply(op2);

jtf_res.setText(""+op1);

break;

case4:

op1=op1.divide(op2,newMathContext(30));

jtf_res.setText(""+op1);

break;

}

currentOp=0;

op2=newBigDecimal("0");

}

}elseif(s.equals(".")){

isBigDecimal=true;

if(jtf_res.getText().trim().indexOf('.')!=-1)

;

else{

if(jtf_res.getText().trim().equals("0")){

str.setLength(0);

jtf_res.setText((str.append("0"+s)).toString());

}elseif(jtf_res.getText().trim().equals("")){

}else{

jtf_res.setText((str.append(s)).toString());

}

}

}elseif(s.equals("0")){

if(jtf_res.getText().trim().equals("0.")){

}else{

jtf_res.setText(str.append(s).toString());

op2=newBigDecimal(jtf_res.getText().trim());

}

}else{

jtf_res.setText(str.append(s).toString());

op2=newBigDecimal(jtf_res.getText().trim());

if(currentOp==0)

op1=op2;

}

}

}

④ 求JAVA用Eclipse写个简易的计算器。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
private final String[] KEYS = { "7", "8", "9", "c", "4", "5", "6",
"+", "1", "2", "3", "-", "0", "*", "/","=" };
//计算器上按键的显示名
private JButton keys[] = new JButton[KEYS.length];
// 计算器上按键的按钮
private JTextField resultText = new JTextField("0");
//计算结果文本框
private boolean firstDigit = true;
//标志用户按的是否是整个表达式的第一个数字,或者是运算符后的第一个数字
private double resultNum = 0.0;
//计算的中间结果
private String operator = "=";
//当前运算的运算符
private boolean operateValidFlag = true; // 操作是否合法

////构造函数

public Calculator ()
{
super();
init(); //初始化计算器
this.setBackground(Color.lightGray); //设置计算器的背景颜色
this.setTitle("计算器");
this.setLocation(100,100);//在屏幕(100,100)坐标处显示计算器
this.setResizable(false);//不许修改计算器的大小
this.setSize(300,250); //使计算器中各组件大小合适
}

////初始化计算器

private void init()
{
resultText.setHorizontalAlignment(JTextField.RIGHT); // 文本框中的内容采用右对齐方式
resultText.setEditable(false); // 不允许修改结果文本框
resultText.setBackground(Color.white); // 设置文本框背景颜色为白色
JPanel calckeysPanel = new JPanel();
//初始化计算器上按键的按钮,将键放在一个画板内
calckeysPanel.setLayout(new GridLayout(4, 4, 10, 15));//用网格布局器,4行,5列的网格,网格之间的水平方向间隔为10个象,垂直方向间隔为15个象素
calckeysPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));//添加画板的边框

for (int i = 0; i < KEYS.length; i++)
{
keys[i] = new JButton(KEYS[i]);
calckeysPanel.add(keys[i]);
}

//整体布局
getContentPane().setLayout(new BorderLayout(3, 5));
getContentPane().add("North", resultText);
getContentPane().add("Center", calckeysPanel);
//为各按钮添加事件侦听器
//都使用同一个事件侦听,即本对象.本类的声明中有implements ActionListener
for (int i = 0; i < KEYS.length; i++)
{
keys[i].addActionListener(this);
}

}
////处理事件

public void actionPerformed(ActionEvent e)
{
String label = e.getActionCommand();//获取事件源的标签

if (e.getSource()==keys[3])
{
handleC(); //用户按了"C"键
}
else if ("0123456789.".indexOf(label) >= 0)
{
handleNumber(label);//用户按了数字键或者小数点键
}
else
{
handleOperator(label); //用户按了运算符键
}
}

////处理数字键被按下的事件

private void handleNumber(String key)
{
if (firstDigit) //输入的第一个数字
{
resultText.setText(key);
}
else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0))
//输入的是小数点,并且之前没有小数点,则将小数点附在结果文本框的后面
{
resultText.setText(resultText.getText() + ".");
}
else if (!key.equals("."))
//如果输入的不是小数点,则将数字附在结果文本框的后面
{
resultText.setText(resultText.getText() + key);
}
firstDigit = false; //以后输入的肯定不是第一个数字了
}

////处理C键被按下的事件

private void handleC()
{
//初始化计算器的各种值
resultText.setText("0");
firstDigit = true;
operator = "=";
}

////处理运算符键被按下的事件

private void handleOperator(String key)
{
if (operator.equals("/")) //除法运算
{
if (getNumberFromText() == 0.0)
//如果当前结果文本框中的值等于0,操作不合法
{
operateValidFlag = false;
resultText.setText("除数不能为零");
}
else
{
resultNum /= getNumberFromText();
}
}
else if (operator.equals("+"))//加法运算
{
resultNum += getNumberFromText();
}
else if (operator.equals("-"))//减法运算
{
resultNum -= getNumberFromText();
}
else if (operator.equals("*")) //乘法运算
{
resultNum *= getNumberFromText();
}
else if (operator.equals("="))//赋值运算
{
resultNum = getNumberFromText();
}
if (operateValidFlag) //双精度浮点数的运算
{
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
resultText.setText(String.valueOf(t1));
} else {
resultText.setText(String.valueOf(resultNum));
}
}
operator = key;//运算符等于用户按的按钮
firstDigit = true;
operateValidFlag = true;
}
////从结果文本框中获取数字

private double getNumberFromText()
{
double result = 0;
try
{
result = Double.valueOf(resultText.getText()).doubleValue();
}
catch (NumberFormatException e)
{}
return result;
}
public static void main(String args[])
{
Calculator calculator1 = new Calculator ();
calculator1.setVisible(true);
calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

凑合写了一个,不过这计算器功能真是少。

⑤ java编写一个计算器类

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Jisuanqi extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Result result = new Result(); // 定义text的面板
Number_Key number_key = new Number_Key(); // 定义按钮面板
// 当点击按钮+、-、*、/时,com = true
boolean com = false;
// 当i=0时说明是我们第一次输入,字符串text不会累加
int i = 0;
// 存放text的内容
String text = "";
// 存放点击按钮+、-、*、/之前的数值
double defbutton = 0;
// +、-、*、/的代号分别为1,2,3,4
int symbol = 0;
// 构造函数
Jisuanqi() {
super("计算器"); // 设定标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设定关闭窗体时退出程序
JPanel pane = new JPanel(); // 定义主面板
pane.setLayout(new BorderLayout());
setBounds(380, 220, 30, 80); // 前两个参数是在屏幕上显示的坐标,后两个是大小
// 替换图标
ImageIcon icon = new ImageIcon("F:1.GIF");
// Jisuanqi.class.getResource("APPLE.GIF")
// );
setIconImage(icon.getImage());
pane.add(result, BorderLayout.NORTH);
pane.add(number_key, BorderLayout.CENTER);
pane.add(number_key.equal, BorderLayout.SOUTH);
number_key.one.addActionListener(this); // 对1按钮添加监听事件
number_key.two.addActionListener(this); // 对2按钮添加监听事件
number_key.three.addActionListener(this); // 对3按钮添加监听事件
number_key.four.addActionListener(this); // 对4按钮添加监听事件
number_key.five.addActionListener(this); // 对5按钮添加监听事件
number_key.six.addActionListener(this); // 对6按钮添加监听事件
number_key.seven.addActionListener(this); // 对7按钮添加监听事件
number_key.eight.addActionListener(this); // 对8按钮添加监听事件
number_key.nine.addActionListener(this); // 对9按钮添加监听事件
number_key.zero.addActionListener(this); // 对0按钮添加监听事件
number_key.ce.addActionListener(this); // 对置零按钮添加监听事件
number_key.plus.addActionListener(this); // 对+按钮添加监听事件
number_key.equal.addActionListener(this); // 对=按钮添加监听事件
number_key.sub.addActionListener(this); // 对-按钮添加监听事件
number_key.mul.addActionListener(this); // 对*按钮添加监听事件
number_key.div.addActionListener(this); // 对/按钮添加监听事件
number_key.point.addActionListener(this); // 对.按钮添加监听事件
setContentPane(pane);
pack(); // 初始化窗体大小为正好盛放所有按钮
}
// 各个按钮触发的事件
public void actionPerformed(ActionEvent e) {
/*
* 如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么com=true 如果没有com=
* false;或者是否点击数字键,如果是i = 1,如果没有 i = 0;
*/
if (e.getSource() == number_key.one) {
if (com || i == 0) {
result.text.setText("1");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "1");
}
} else if (e.getSource() == number_key.two) {
if (com || i == 0) {
result.text.setText("2");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "2");
}
} else if (e.getSource() == number_key.three) {
if (com || i == 0) {
result.text.setText("3");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "3");
}
} else if (e.getSource() == number_key.four) {
if (com || i == 0) {
result.text.setText("4");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "4");
}
} else if (e.getSource() == number_key.five) {
if (com || i == 0) {
result.text.setText("5");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "5");
}
} else if (e.getSource() == number_key.six) {
if (com || i == 0) {
result.text.setText("6");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "6");
}
} else if (e.getSource() == number_key.seven) {
if (com || i == 0) {
result.text.setText("7");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "7");
}
} else if (e.getSource() == number_key.eight) {
if (com || i == 0) {
result.text.setText("8");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "8");
}
} else if (e.getSource() == number_key.nine) {
if (com || i == 0) {
result.text.setText("9");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "9");
}
}
/*
* 对于0这个按钮有一定的说法,在程序里不会出现如00000这样的情况,加了判断条件就是
* 如果text中的数值=0就要判断在这个数值中是否有.存在?如果有那么就在原来数值基础之上添 加0;否则保持原来的数值不变
*/
else if (e.getSource() == number_key.zero) { // result.text.getText()是得到text里内容的意思
if (com || i == 0) {
result.text.setText("0");
com = false;
i = 1;
} else {
text = result.text.getText();
if (Float.parseFloat(text) > 0 || Float.parseFloat(text) < 0) { // Float.parseFloat(text)就是类型转换了,下面都是一样
result.text.setText(text + "0");
} else {
if (text.trim().indexOf(".") == -1) {
result.text.setText(text);
} else {
result.text.setText(text + "0");
}
}
}
} else if (e.getSource() == number_key.ce) {
result.text.setText("0");
i = 0;
com = true;
// text = "";
defbutton = 0;
}
/*
* 本程序不会让一个数值中出现2个以上的小数点.具体做法是:判断是否已经存在.存在就不添加, 不存在就添加.
*/
else if (e.getSource() == number_key.point) {
if (com || i == 0) {
result.text.setText("0.");
com = false;
i = 1;
} else {
text = result.text.getText();
if (text.trim().indexOf(".") == -1) {
result.text.setText(text + ".");
} else {
result.text.setText(text);
}
}
} // 获得点击+之前的数值
else if (e.getSource() == number_key.plus) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 1;
} // 获得点击-之前的数值
else if (e.getSource() == number_key.sub) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 2;
} // 获得点击*之前的数值
else if (e.getSource() == number_key.mul) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol = 3;
} // 获得点击/之前的数值
else if (e.getSource() == number_key.div) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 4;
} else if (e.getSource() == number_key.equal) {
switch (symbol) {
case 1: { // 计算加法
double ad = defbutton
+ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 2: { // 计算减法
double ad = defbutton
- Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i = 0;
text = "";
break;
}
case 3: { // 计算乘法
double ad = defbutton
* Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 4: { // 计算除法
double ad = defbutton
/ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
}
System.out.println(com);
}
System.out.println(result.text.getText());
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Jisuanqi loveyou = new Jisuanqi();
loveyou.show();
}
}
// 计算器数字按钮定义面板
class Number_Key extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton zero = new JButton("0"); // 数字键0
JButton one = new JButton("1"); // 数字键1
JButton two = new JButton("2"); // 数字键2
JButton three = new JButton("3"); // 数字键3
JButton four = new JButton("4"); // 数字键4
JButton five = new JButton("5"); // 数字键5
JButton six = new JButton("6"); // 数字键6
JButton seven = new JButton("7"); // 数字键7
JButton eight = new JButton("8"); // 数字键8
JButton nine = new JButton("9"); // 数字键9
JButton plus = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div = new JButton("/");
JButton equal = new JButton("=");
JButton ce = new JButton("清零"); // 置零键
JButton point = new JButton(".");
Number_Key() {
setLayout(new GridLayout(4, 4, 1, 1)); // 定义布局管理器为网格布局
setBackground(Color.blue); // 设置背景颜色
// 添加按钮
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
add(plus);
add(sub);
add(mul);
add(div);
add(point);
add(equal);
add(ce);
}
}
// 计算器显示结果的窗体
class Result extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// text先是输入和结果
JTextField text = new JTextField("0");
@SuppressWarnings("deprecation")
Result() { // 讲输入的数字或得到的结果在text的右边显示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false); // 文本框不能编辑
setLayout(new BorderLayout()); // 设定布局管理器边框布局
add(text, BorderLayout.CENTER); // text放置在窗体的中间
}
}

⑥ 用java编写一个简单的计算器类

这个是有界面的,自己改一些就可以了。。
---------------------------------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

class Stack_Float
{
float nums[];
int top;

Stack_Float()
{
nums = new float[50];
top = -1;
}

boolean IsEmpty()
{
if (top == -1)
return true;
else
return false;
}

float Pop_Stack()
{
if (top == -1)
{
return 0;
}
top--;
return nums[top + 1];
}

float GetTop()
{
return nums[top];
}

void Push_Stack(float num)
{
if (top == 49)
return;
top++;
nums[top] = num;
}
}

class Stack_Char
{
char str[];
int top;

Stack_Char()
{
str = new char[50];
top = -1;
}

boolean CanPush(char c)
{
int temp = top;
if (c == '(')
{
while (temp != -1)
{
if (str[temp] == '(')
{
return false;
}
temp--;
}
}
temp = top;
if (c == '[')
{
while (temp != -1)
{
if (str[temp] == '[' || str[temp] == '(')
{
return false;
}
temp--;
}
}
if (c == '{')
{
while (temp != -1)
{
if (str[temp] == '{' || str[temp] == '[' || str[temp] == '(')
{
return false;
}
temp--;
}
}
return true;
}

boolean IsEmpty()
{
if (top == -1)
return true;
else
return false;
}

void Push_Stack(char ch)
{
if (top == 49)
return;
top++;
str[top] = ch;
}

char Pop_Stack()
{
if (top == -1)
return '\0';
top--;
return str[top + 1];
}

char GetTop()
{
if (top == -1)
{
System.out.print("error");
System.exit(0);
}
return str[top];
}
}

public class jisuanqi extends javax.swing.JFrame implements ActionListener
{
JTextField text = new JTextField();
JTextField text1 = new JTextField();
JButton jButton1 = new JButton();
JButton jButton2 = new JButton();
JButton jButton3 = new JButton();
JButton jButton4 = new JButton();
JButton jButton5 = new JButton();
JButton jButton6 = new JButton();
JButton jButton7 = new JButton();
JButton jButton8 = new JButton();
JButton jButton9 = new JButton();
JButton jButton10 = new JButton();
JButton jButton11 = new JButton();
JButton jButton12 = new JButton();
JButton jButton13 = new JButton();
JButton jButton14 = new JButton();
JButton jButton15 = new JButton();
JButton jButton16 = new JButton();
JButton jButton17 = new JButton();
JButton jButton18 = new JButton();
JButton jButton19 = new JButton();
JButton jButton20 = new JButton();
JButton jButton21 = new JButton();
JButton jButton22 = new JButton();
String show = "";

public jisuanqi()
{
initComponents();
}

char[] TranSmit(char str[])
{
char houzhui[] = new char[50]; // 存放后缀表达式的字符串
int i = 0, j = 0;
char c = str[i];
Stack_Char s = new Stack_Char(); // 存放运算符的栈
while (c != '=') // 对算术表达式扫描未结束时
{
if (c >= '0' && c <= '9')
{
while (c >= '0' && c <= '9')// 数字直接入栈
{
houzhui[j] = c;
j++;
i++;
c = str[i];
}
houzhui[j] = '#';// 用#隔开数字
j++;
}
switch (c) // 扫描到运算符时
{
case '+':
case '-':
case '*':
case '/':
case '(':
case '[':
case '{':
if (s.IsEmpty() == true) // 栈空,直接入栈
{
s.Push_Stack(c);
i++;
c = str[i];
break;
}
if (ComPare(s.GetTop(), c) == -1) {
s.Push_Stack(c); // 入栈
i++;
c = str[i];
break;
}
if (ComPare(s.GetTop(), c) == 1) {
houzhui[j] = s.Pop_Stack();// 出栈元素存入后缀表达式
j++;
break;
}

case ')': // 扫描到 )
while (s.GetTop() != '(') // 未扫描到 ( 时,出栈
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '(' 出栈
i++;
c = str[i];
break;
case ']': // 扫描到 ]
while (s.GetTop() != '[') // 未扫描到 [ 时,出栈
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '[' 出栈
i++;
c = str[i];
break;
case '}': // 扫描到 }
while (s.GetTop() != '{') // 未扫描到 { 时,出栈
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '{' 出栈
i++;
c = str[i];
break;
}
}
while (s.IsEmpty() != true)// 把剩余的运算符直接出栈
{
houzhui[j] = s.Pop_Stack();
j++;
}
houzhui[j] = '=';// 后缀表达式后面加 =
j++;
houzhui[j] = '\0';
j++;
return houzhui;
}

float Count(char str[])
{
Stack_Float s = new Stack_Float();// 定义存放数字的栈
char c = str[0];
int i = 0;
float result = 0, temp, left, right;
while (c != '=') // 未扫描到 = 时
{
if (c >= '0' && c <= '9')// 扫描到数字
{
temp = 0;
while (c != '#')// 未读到分隔符时
{
temp = temp * 10 + c - '0';
i++;
c = str[i];
}
s.Push_Stack(temp);// 进栈
}
switch (c)// 扫描到运算符时
{
case '+':
{
result = s.Pop_Stack() + s.Pop_Stack();// 2个数字出栈相加
s.Push_Stack(result);// 最后得数进栈
break;
}
case '-':
{
right = s.Pop_Stack();// 右操作数出栈
left = s.Pop_Stack();// 左操作数出栈
result = left - right;
s.Push_Stack(result);
break;
}
case '*':
{
result = s.Pop_Stack() * s.Pop_Stack();// 2个数字出栈相乘
s.Push_Stack(result);
break;
}
case '/':
{
right = s.Pop_Stack();// 右操作数出栈
left = s.Pop_Stack();// 左操作数出栈
result = left / right;
s.Push_Stack(result);
break;
}
}
i++;
c = str[i];
}
return result;
}

int ComPare(char a, char b) // 判断运算符的优先级函数
{
int s[][] = {// 栈顶元素高于算术表达式中的元素时, 返回 1,否则返回 -1
{ 1, 1, -1, -1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, -1, -1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, 1, 1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, 1, 1, -1, 1, -1, 1, -1, 1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, 1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, -1, -1, -1, -1, 1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, -1, -1, -1, -1, -1 } };

char x1[] = { '+', '-', '*', '/', '(', ')', '[', ']', '{', '}' };// 栈顶元素
char x2[] = { '+', '-', '*', '/', '(', ')', '[', ']', '{', '}' };// 算术表达式中的元素
int k = 0, m, n = 0;
for (m = 0; m < 10; m++) // 查找2个进行比较的运算符在表中的位置,并返回比较结果
{
for (n = 0; n < 10; n++)
{
if (x1[m] == a && x2[n] == b)
{
k = 1;
break; // 找到比较结果后,跳出循环
}
}
if (k == 1)
break;
}
return s[m][n];// 返回比较结果
}

public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jButton1)
{
show += "1";
text.setText(show);
}
if (e.getSource() == jButton2)
{
show += "2";
text.setText(show);
}
if (e.getSource() == jButton3)
{
show += "3";
text.setText(show);
}
if (e.getSource() == jButton4)
{
show += "4";
text.setText(show);
}
if (e.getSource() == jButton5)
{
show += "5";
text.setText(show);
}
if (e.getSource() == jButton6)
{
show += "6";
text.setText(show);
}
if (e.getSource() == jButton7)
{
show += "7";
text.setText(show);
}
if (e.getSource() == jButton8)
{
show += "8";
text.setText(show);
}
if (e.getSource() == jButton9)
{
show += "9";
text.setText(show);
}
if (e.getSource() == jButton10)
{
show += "0";
text.setText(show);
}
if (e.getSource() == jButton11)
{
show += "+";
text.setText(show);
}
if (e.getSource() == jButton12)
{
show += "-";
text.setText(show);
}
if (e.getSource() == jButton13)
{
show += "*";
text.setText(show);
}
if (e.getSource() == jButton14)
{
show += "/";
text.setText(show);
}
if (e.getSource() == jButton15)
{
show += "(";
text.setText(show);
}
if (e.getSource() == jButton16)
{
show += ")";
text.setText(show);
}
if (e.getSource() == jButton17)
{
show += "[";
text.setText(show);
}
if (e.getSource() == jButton18)
{
show += "]";
text.setText(show);
}
if (e.getSource() == jButton19)
{
show += "{";
text.setText(show);
}
if (e.getSource() == jButton20)
{
show += "}";
text.setText(show);
}
if (e.getSource() == jButton21)
{
show = "";
text.setText("");
text1.setText("");
}
if (e.getSource() == jButton22)
{
show += "=";
text.setText(show);

char str1[] = new char[50];
char str2[] = new char[50];
float result = 0;

str1 = show.toCharArray();
str2 = TranSmit(str1);
result = Count(str2);

text1.setText((new String(str2)).trim());
text.setText("" + result);
show = "";
}
}

private void initComponents()
{
text.setBounds(10, 10, 270, 30);
text1.setBounds(10, 50, 270, 30);
jButton1.setBounds(10, 90, 60, 25);
jButton2.setBounds(80, 90, 60, 25);
jButton3.setBounds(150, 90, 60, 25);
jButton4.setBounds(220, 90, 60, 25);
jButton5.setBounds(10, 120, 60, 25);
jButton6.setBounds(80, 120, 60, 25);
jButton7.setBounds(150, 120, 60, 25);
jButton8.setBounds(220, 120, 60, 25);
jButton9.setBounds(10, 150, 60, 25);
jButton10.setBounds(80, 150, 60, 25);
jButton11.setBounds(150, 150, 60, 25);
jButton12.setBounds(220, 150, 60, 25);
jButton13.setBounds(10, 180, 60, 25);
jButton14.setBounds(80, 180, 60, 25);
jButton15.setBounds(150, 180, 60, 25);
jButton16.setBounds(220, 180, 60, 25);
jButton17.setBounds(150, 210, 60, 25);
jButton18.setBounds(220, 210, 60, 25);
jButton19.setBounds(10, 210, 60, 25);
jButton20.setBounds(80, 210, 60, 25);
jButton21.setBounds(10, 240, 60, 25);
jButton22.setBounds(80, 240, 60, 25);

jButton1.setText("1");
jButton2.setText("2");
jButton3.setText("3");
jButton4.setText("4");
jButton5.setText("5");
jButton6.setText("6");
jButton7.setText("7");
jButton8.setText("8");
jButton9.setText("9");
jButton10.setText("0");
jButton11.setText("+");
jButton12.setText("-");
jButton13.setText("*");
jButton14.setText("/");
jButton15.setText("(");
jButton16.setText(")");
jButton17.setText("[");
jButton18.setText("]");
jButton19.setText("{");
jButton20.setText("}");
jButton21.setText("CE");
jButton22.setText("=");

jButton1.addActionListener(this);
jButton2.addActionListener(this);
jButton3.addActionListener(this);
jButton4.addActionListener(this);
jButton5.addActionListener(this);
jButton6.addActionListener(this);
jButton7.addActionListener(this);
jButton8.addActionListener(this);
jButton9.addActionListener(this);
jButton10.addActionListener(this);
jButton11.addActionListener(this);
jButton12.addActionListener(this);
jButton13.addActionListener(this);
jButton14.addActionListener(this);
jButton15.addActionListener(this);
jButton16.addActionListener(this);
jButton17.addActionListener(this);
jButton18.addActionListener(this);
jButton19.addActionListener(this);
jButton20.addActionListener(this);
jButton21.addActionListener(this);
jButton22.addActionListener(this);

add(text);
add(text1);
add(jButton1);
add(jButton2);
add(jButton3);
add(jButton4);
add(jButton5);
add(jButton6);
add(jButton7);
add(jButton8);
add(jButton9);
add(jButton10);
add(jButton11);
add(jButton12);
add(jButton13);
add(jButton14);
add(jButton15);
add(jButton16);
add(jButton17);
add(jButton18);
add(jButton19);
add(jButton20);
add(jButton21);
add(jButton22);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setBounds(300, 300, 300, 300);
setVisible(true);
}

public static void main(String args[])
{
new jisuanqi();
}
}

阅读全文

与java设计简易计算器相关的资料

热点内容
云计算服务器贵州云空间 浏览:33
登录服务器login输入什么 浏览:878
三点指标公式源码 浏览:544
黑马程序员fetch教程 浏览:442
不用编程的游戏引擎 浏览:533
点菜pdf 浏览:82
圣经pdf下载 浏览:291
如何打印到pdf文件 浏览:557
石碣CNC编程 浏览:553
程序员那么可爱31集上中下完整版 浏览:819
有什么动漫app是可以免费看的 浏览:141
程序员语言有多少种 浏览:198
linux系统对硬盘分区 浏览:267
php7性能优化总结 浏览:820
pdf文本格式转换器 浏览:116
androidmap排序 浏览:450
php类型自动 浏览:213
一键apk反编译提取视频文件 浏览:981
linuxshell释放缓存命令 浏览:72
路由器服务器主机名怎么设置 浏览:992