Java程序编写一个计算器类,要求实现加、减、乘、除运算,注意在进行除法运算时,如果除数为0,

1. 编写一个计算器类,要求实现加、减、乘、除运算,注意在进行除法运算时,如果除数为0,要对用户进行错误提示。采用键盘输入方式。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Caculator extends JFrame implements KeyListener{ //构造Caculator类
private Container content;//构造容器
private JButton bCancel; //清除按钮
private JButton[] b=new JButton[16]; //构造按钮数组
private char LastOp; //操作符号
private boolean Countable; //用于判断是否可计算
private String KeyLabel[]={"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};
private StringBuffer str;
private JPanel KeyPanel,TextPanel; //按键面板,结果面板
private JTextArea tResult; //用于显示结果的文本域
private double x=0,y=0; //操作数
public Caculator(){
setTitle("袖珍计算器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content =getContentPane(); //初始化一个容器
content.setLayout(new BorderLayout()); //设置容器的布局方式
KeyPanel=new JPanel();
TextPanel=new JPanel();
TextPanel.setLayout(new FlowLayout()); //设置TextPanel面板的布局方式
KeyPanel.setLayout(new GridLayout(4,4)); //设置KeyPanel面板的布局方式
tResult=new JTextArea(1,15); //实例化一个JTextArea类
tResult.setEditable(false); //将tResult设置为不可编辑
tResult.setText("0"); //文本域显示为0
tResult.addKeyListener(this); //添加键盘监听器
str=new StringBuffer(); //实例化一个字符串缓冲区

ButtonListener btnListener = new ButtonListener(); //实例化一个ButtonListener类的监听器
for(int i=0;i<16;i++){
b[i] = new JButton(KeyLabel[i]);
b[i].addActionListener(btnListener); //添加ButtonListener类监听器
b[i].addKeyListener(this); //添加键盘监听器
KeyPanel.add(b[i]);
}
bCancel=new JButton("C");
bCancel.addActionListener(btnListener); //添加ButtonListener类监听器
bCancel.addKeyListener(this); //添加键盘监听器
bCancel.setBackground(Color.RED);
LastOp='!'; //若LastOp的值不为'+' '-' '*' '/'中的一个,则约定它的值是 '!'
Countable=false;

TextPanel.add(tResult);
TextPanel.add(bCancel);
content.add("North",TextPanel);
content.add("Center",KeyPanel);
pack();
setResizable(false);
setVisible(true);
}
class ButtonListener implements ActionListener //构造监听器
{
public void actionPerformed(ActionEvent e) {
String s = ((JButton)e.getSource()).getText().trim(); //得到用户按下的按钮上的文本
char c = s.charAt(0); //得到s中索引为0的字符

if(c == 'C') //选择按钮C
{
tResult.setText("0");
str.setLength(0);
LastOp = '!';
Countable = false;
x = 0;
y = 0;
return;
}


if(c == '.') //选择输入小数点
{
if( tResult.getText().trim().indexOf(".") != -1) return;
else
{ str.insert(str.length(),".");
tResult.append(".");
return;
}
}
if(c == '+'||c == '-'||c == '*'||c == '/'||c == '=') //按加减乘除或等号键
{
Caculate(c);
return;
}

//剩下的数字键
tResult.setText(str.append(s).toString());
Countable=true;
}
}

//实现KeyListener监听器
public void keyTyped(KeyEvent ek)
{
char c = ek.getKeyChar(); //获取键盘上按的数字键
if(c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9'||c=='0')
{
tResult.setText(str.append(c).toString());
Countable=true;
return;
}
if(c =='.') //按小数点
{
if( tResult.getText().trim().indexOf(".") != -1) return;
else
{ str.insert(str.length(),".");
tResult.append(".");
return;
}
}

if((int)c == KeyEvent.VK_DELETE ) //按delete键
{
tResult.setText("0");
str.setLength(0);
LastOp = '!';
Countable = false;
x = 0;
y = 0;
return;
}
if(c == '+'||c == '-'||c == '*'||c == '/'||c == '=') //按加减乘除或等号键
{
Caculate(c);
return;
}
}
public void keyPressed(KeyEvent ek) {}
public void keyReleased(KeyEvent ek) {}
public void Caculate(char c)
{
if(c == '+') //按加号键
{
Add();
return;
}

if( c == '-') //按减号键
{
Minus();
return;
}
if(c == '*') //按乘号键
{
Mul();
return;
}
if(c == '/') //按除号
{
Div();
return;
}
if(c == '=') //按等号键
{
Equal();
return;
}
}
public void Add(){ //加方法
if(Countable==true && LastOp != '!') //判断是否进行运算
{
y = Double.parseDouble(tResult.getText().trim());
switch(LastOp)
{
case '+' : x = x+y; break;
case '-' : x = x-y; break;
case '*' : x = x*y; break;
case '/' :if(y != 0) x = x/y;
else
{
tResult.setText("除数不能为0");return;
}
}
tResult.setText(""+x);
Countable = false;
}
else x = Double.parseDouble(tResult.getText().trim());
str.setLength(0);
y = 0;
LastOp = '+';
return ;
}
public void Minus(){ //减方法
if(Countable==true && LastOp != '!') //判断是否进行运算
{
y = Double.parseDouble(tResult.getText().trim());
switch(LastOp)
{
case '+' : x = x+y; break;
case '-' : x = x-y; break;
case '*' : x = x*y; break;
case '/' :if(y != 0) x = x/y;
else
{
tResult.setText("除数不能为0");return;
}
}
tResult.setText(""+x);
Countable = false;
}
else x = Double.parseDouble(tResult.getText().trim());
str.setLength(0);
y = 0;
LastOp = '-';
return ;
}
public void Mul(){ //乘方法
if(Countable==true && LastOp != '!') //判断是否进行运算
{
y = Double.parseDouble(tResult.getText().trim());
switch(LastOp)
{
case '+' : x = x+y; break;
case '-' : x = x-y; break;
case '*' : x = x*y; break;
case '/' :if(y != 0) x = x/y;
else
{
tResult.setText("除数不能为0");return;
}
}
tResult.setText(""+x);
Countable = false;
}
else x = Double.parseDouble(tResult.getText().trim());
str.setLength(0);
y = 0;
LastOp = '*';
return ;
}
public void Div() //除方法
{
if(Countable==true && LastOp != '!') //判断是否进行运算
{
y = Double.parseDouble(tResult.getText().trim());
switch(LastOp)
{
case '+' : x = x+y; break;
case '-' : x = x-y; break;
case '*' : x = x*y; break;
case '/' :if(y != 0) x = x/y;
else
{
tResult.setText("除数不能为0");return;
}
}
tResult.setText(""+x);
Countable = false;
}
else x = Double.parseDouble(tResult.getText().trim());
str.setLength(0);
y = 0;
LastOp = '/';
return ;
}
public void Equal() //求结果的方法
{
y = Double.parseDouble(tResult.getText().trim());
switch(LastOp)
{
case '+' : x = x+y; break;
case '-' : x = x-y; break;
case '*' : x = x*y; break;
case '/' :if(y != 0) x = x/y;
else
{
tResult.setText("除数不能为0");return;
}
}
tResult.setText(""+x);
Countable=false;
return;
}
public static void main(String args[])
{
Caculator cal=new Caculator();
}
}追问

能否给一个简单的计算机程序呢

追答public class Hello{
public static void main(String[] args){
java.util.Scanner sc = new java.util.Scanner(System.in);
try{
System.out.println("请输入要运算的第一个数..");
float f1 = sc.nextFloat();
System.out.println("输入运算符+ - * /(默认不输入为+).");
char fu = '+';
//String fuhao = next();
try{
char[] zhuan = sc.next().toCharArray();
fu = zhuan[0];
}catch(Exception e){System.out.println("运算符输入错误");}
System.out.println("请输入要运算的第二个数..");
float f2 = sc.nextFloat();
switch(fu){
case '+':
System.out.println("加法:" + (f1 + f2));
break;
case '-':
System.out.println("减法:" + (f1 - f2));
break;
case '/':
if(f2 == 0){
System.out.println("被除数不能为0");
}else{
System.out.println("除法:" + (f1 / f2));
}
break;
case '*':
System.out.println("乘法:" + (f1 * f2));
break;
default :
System.out.println("不存在的符号");
}

}catch(Exception e){System.out.println("请输入数字或小数");}
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2018-01-16
用Java定义一个类,实现加减乘除计算功能,把结果输出?

Java程序编写一个计算器类,要求实现加、减、乘、除运算,注意在进行除 ...
\/\/操作符号private boolean Countable; \/\/用于判断是否可计算private String KeyLabel[]={"7","8","9","\/","4","5","6","*","1","2","3","-","0","."

用Java编写计算器
import java.util.regex.*;public class Calculation { public static void main(String[] args) throws Exception { \/\/ TODO Auto-generated method stub if (args.length != 3) { System.out.println("MyCal need 3 parameters the formate is:");System.out.println("MyCal num1 operate num2...

求JAVA编写的 简易计算器程序,附上注释
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Calculator implements ActionListener { String s="",s1;double d1,d2;JFrame jf = new JFrame("小计算器by Graduate") ;JTextField tf = new JTextField();public void init()\/\/实现计算器界面 { Container c...

java:编写一个计算器小程序,要求可以做加减乘除运算
private JTextField text_double;\/\/ = new JTextField("0");private String operator = "="; \/\/当前运算的运算符 private boolean firstDigit = true; \/\/ 标志用户按的是否是整个表达式的第一个数字,或者是运算符后的第一个数字 private double resultNum = 0.0; \/\/ 计算的中间结果 private boo...

用JAVA编写一个计算器
\/\/ 计算器数字按钮定义面板class Number_Key extends JPanel {\/*** *\/private static final long serialVersionUID = 1L;JButton zero = new JButton("0"); \/\/ 数字键0JButton one = new JButton("1"); \/\/ 数字键1JButton two = new JButton("2"); \/\/ 数字键2JButton three = new JButton...

设计一个能够完成加、减、乘、除、取余等运算的简单计算器
所要求的程序已经完成,取余数用%作运算符。请采纳:Private Sub Command1_Click()x = Val(Text1.Text)op = Text2.Text y = Val(Text3.Text)If y = 0 And (op = "%" Or op = "\/") Then MsgBox ("除法运算中除数不能为0!")Exit Sub End If Select Case op Case "+":MsgBox ...

急!用JAVA编一个小型计算器
用图形界面工具,结合事件处理机制,编写Java Application程序,实现一个可视化的计算器。三、实验要求:1. 必须采用一种布局管理器;2. 使用标签、按钮、文本框绘制一个计算器(至少应具有按键和显示区,至少实现加、减、乘、除运算);3. 采用一种合适的事件处理器;4. 写出实验报告。请知道的高手们给我解答,谢谢!!!

用java程序编写一个计算器
private String num1 = "";\/\/保存第一个运算数字 private String operator = "";\/\/保存运算符号 public static void main(String[] args) { new Calculator();\/\/new计算器实例 } public Calculator(){ \/\/添加组件,布局 inputPanel.add(input);f.add(inputPanel, BorderLayout.NORTH);operation...

编写一个能够循环执行的运算器程序,完成加法、减法、乘法和除法。两个...
double result = 0.0;do{getOption (&option); \/\/显示菜单,读选项if (option != 5){getNumbers(&a, &b, option);\/\/读两个操作数,若为除法,判别除数不为零若除数为零,要求用户重新输入calc(a, b ,option, &result);\/\/ 完成运算,并返回结果printResult(a, b, option, result);\/\/...

求一个JAVA程序
import java.applet.*;\/\/定义类Calculator.javapublic class Calculator extends Applet{ private TextField tfAnswer;\/\/计算器的显示文本框 private Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;\/\/数字0~9的按钮 \/\/定义小数点,等于号,加,减,清零,乘和除等按钮 private Button bPoint,bEqual,bPlus,bMinus,...

相似回答