java计算器代码带注释 java计算器代码解析
求:Java 计算器加减乘除代码 注释
public class MyComputer implements ActionListener{
成都创新互联是一家集网站建设,新干企业网站建设,新干品牌网站建设,网站定制,新干网站建设报价,网络营销,网络优化,新干网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
private boolean appendnumber = false;
private boolean append = false;
private boolean flag = false;
private String temp1 = null;
private String op1 = null;
private JTextField jtf = new JTextField("0.",28);
public MyComputer(){
init();
}
private void init() {
/*
* 下面都是在画计算机界面你想看也可以,
* 不看也行,具体计算在public void
* actionPerformed(ActionEvent e)
* 里
*/
JFrame frame = new JFrame("我的计算器");
JPanel panelTop = new JPanel();
panelTop.setLayout(new FlowLayout());
panelTop.add(jtf);
JPanel panelBotton = new JPanel();
String[] str = {"BackSpace","CE","C","+",
"7","8","9","-",
"4","5","6","*",
"1","2","3","/",
"0","+/-",".","="};
JButton[] jb = new JButton[str.length];
panelBotton.setLayout(new GridLayout(5,4));
for(int i = 0;i jb.length;i++)
{
jb[i] = new JButton(str[i]);
panelBotton.add(jb[i]);
jb[i].addActionListener(this);
}
frame.add(panelTop,BorderLayout.NORTH);
frame.add(panelBotton);
frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
new MyComputer();
}
public void actionPerformed(ActionEvent e) {
String comm = e.getActionCommand();//获得button里的数据
/*
* "0123456789".indexOf(comm)!=-1是判断button里获得的数据
* 是0---9的情况
*/
if ("0123456789".indexOf(comm)!=-1) {
if(!appendnumber){
jtf.setText(comm);
appendnumber = true;
}else{
jtf.setText(jtf.getText()+comm);
}
}
/*
* 判断button里获得的数据是加减乘除的情况
*/
if("+-*/".indexOf(comm)!=-1){
//在遇到加减乘除的符号时我们先存储刚输入的值
temp1 = jtf.getText();
//然后存储符号
op1 = comm;
/*
* 然后可以重新输入数据到输入框,所以这时候我们
* 不能追加数据,设置追加数据标志为false
*/
appendnumber = false;
}
/*
* 判断button里获得的数据是等号的情况
*/
else if("=".equals(comm)) {
if(temp1==null||"".equals(temp1))return;
/*
* 遇到等号的时候,我们取出刚才保存的数据和当前输入的数据做运算
*/
double num1 = Double.parseDouble(temp1);//转化数据成double型的
double num2 = Double.parseDouble(jtf.getText());//转化数据成double型的
//取出刚才保存的符号看是加减乘除的那种运算
if("+".equals(op1)){
num1+=num2;
}
if("-".equals(op1)){
num1-=num2;
}
if ("*".equals(op1)) {
num1*=num2;
}
if("/".equals(op1)){
num1/=num2;
}
jtf.setText(num1+"");
appendnumber = false;
}
/*
* 判断button里获得的数据是小数点的情况
*/
else if (".".equals(comm)) {
if(jtf.getText().indexOf(".")==-1){
append = true;
}
if (append) {
jtf.setText(jtf.getText()+".");
append = false;
appendnumber = true;
}
}
/*
* 判断button里获得的数据是在数据前面加正负号的情况
*/
else if ("+/-".equals(comm)) {
if(!flag){
jtf.setText("-"+jtf.getText());
flag = true;
}
else{
String result = jtf.getText().substring(1, jtf.getText().length());
jtf.setText(result);
flag = false;
}
}
/*
* 判断button里获得的数据是清除输入框的情况
*/
else if ("C".equals(comm)) {
jtf.setText("0.");
appendnumber = false;
}
/*
* 判断button里获得的数据是清除输入框的情况
*/
else if ("CE".equals(comm)) {
jtf.setText("0.");
appendnumber = false;
}
/*
* 判断button里获得的数据是输入框的数据退一位的情况
*/
else if ("BackSpace".equals(comm)) {
if(jtf.getText()==null||"".equals(jtf.getText()))return;
String result = jtf.getText().substring(0, jtf.getText().length()-1);
jtf.setText(result+"");
appendnumber = true;
}
}
}
很简单的东西啊!你们去分那么多情况啊!这个东西啊一个人写半个小时就OK了,如果你会写的话,其实初学者们别因为别人怎么怎么说就吓倒,其实这写起来都没多少代码的,都是些小东西而已。最重要的是你要搞懂来龙去脉就不难了,别听一些人吹谁谁牛X这类的,其实你认真的去做,认真的去思考,你也不比他们差。
JAVA语言计算器程序注释
我有一个计算器程序,有代码:
package book.gui;
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;
/**
* 一个计算器,与Windows附件自带计算器的标准版功能、界面相仿。
* 但还不支持键盘操作。
*/
public class Calculator extends JFrame implements ActionListener {
/** 计算器上的键的显示名字 */
private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6",
"*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
/** 计算器上的功能键的显示名字 */
private final String[] COMMAND = { "Backspace", "CE", "C" };
/** 计算器左边的M的显示名字 */
private final String[] M = { " ", "MC", "MR", "MS", "M+" };
/** 计算器上键的按钮 */
private JButton keys[] = new JButton[KEYS.length];
/** 计算器上的功能键的按钮 */
private JButton commands[] = new JButton[COMMAND.length];
/** 计算器左边的M的按钮 */
private JButton m[] = new JButton[M.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.LIGHT_GRAY);
this.setTitle("计算器");
//在屏幕(500, 300)坐标处显示计算器
this.setLocation(500, 300);
//不许修改计算器的大小
this.setResizable(false);
//使计算器中各组件大小合适
this.pack();
}
/**
* 初始化计算器
*/
private void init() {
// 文本框中的内容采用右对齐方式
resultText.setHorizontalAlignment(JTextField.RIGHT);
// 不允许修改结果文本框
resultText.setEditable(false);
// 设置文本框背景颜色为白色
resultText.setBackground(Color.white);
//初始化计算器上键的按钮,将键放在一个画板内
JPanel calckeysPanel = new JPanel();
//用网格布局器,4行,5列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素
calckeysPanel.setLayout(new GridLayout(4, 5, 3, 3));
for (int i = 0; i KEYS.length; i++) {
keys[i] = new JButton(KEYS[i]);
calckeysPanel.add(keys[i]);
keys[i].setForeground(Color.blue);
}
//运算符键用红色标示,其他键用蓝色表示
keys[3].setForeground(Color.red);
keys[8].setForeground(Color.red);
keys[13].setForeground(Color.red);
keys[18].setForeground(Color.red);
keys[19].setForeground(Color.red);
//初始化功能键,都用红色标示。将功能键放在一个画板内
JPanel commandsPanel = new JPanel();
//用网格布局器,1行,3列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素
commandsPanel.setLayout(new GridLayout(1, 3, 3, 3));
for (int i = 0; i COMMAND.length; i++) {
commands[i] = new JButton(COMMAND[i]);
commandsPanel.add(commands[i]);
commands[i].setForeground(Color.red);
}
//初始化M键,用红色标示,将M键放在一个画板内
JPanel calmsPanel = new JPanel();
//用网格布局管理器,5行,1列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素
calmsPanel.setLayout(new GridLayout(5, 1, 3, 3));
for (int i = 0; i M.length; i++) {
m[i] = new JButton(M[i]);
calmsPanel.add(m[i]);
m[i].setForeground(Color.red);
}
//下面进行计算器的整体布局,将calckeys和command画板放在计算器的中部,
//将文本框放在北部,将calms画板放在计算器的西部。
//新建一个大的画板,将上面建立的command和calckeys画板放在该画板内
JPanel panel1 = new JPanel();
//画板采用边界布局管理器,画板里组件之间的水平和垂直方向上间隔都为3象素
panel1.setLayout(new BorderLayout(3, 3));
panel1.add("North", commandsPanel);
panel1.add("West", calckeysPanel);
//建立一个画板放文本框
JPanel top = new JPanel();
top.setLayout(new BorderLayout());
top.add("Center", resultText);
//整体布局
getContentPane().setLayout(new BorderLayout(3, 5));
getContentPane().add("North", top);
getContentPane().add("Center", panel1);
getContentPane().add("West", calmsPanel);
//为各按钮添加事件侦听器
//都使用同一个事件侦听器,即本对象。本类的声明中有implements ActionListener
for (int i = 0; i KEYS.length; i++) {
keys[i].addActionListener(this);
}
for (int i = 0; i COMMAND.length; i++) {
commands[i].addActionListener(this);
}
for (int i = 0; i M.length; i++) {
m[i].addActionListener(this);
}
}
/**
* 处理事件
*/
public void actionPerformed(ActionEvent e) {
//获取事件源的标签
String label = e.getActionCommand();
if (label.equals(COMMAND[0])){
//用户按了"Backspace"键
handleBackspace();
} else if (label.equals(COMMAND[1])) {
//用户按了"CE"键
resultText.setText("0");
} else if (label.equals(COMMAND[2])){
//用户按了"C"键
handleC();
} else if ("0123456789.".indexOf(label) = 0) {
//用户按了数字键或者小数点键
handleNumber(label);
// handlezero(zero);
} else {
//用户按了运算符键
handleOperator(label);
}
}
/**
* 处理Backspace键被按下的事件
*/
private void handleBackspace() {
String text = resultText.getText();
int i = text.length();
if (i 0) {
//退格,将文本最后一个字符去掉
text = text.substring(0, i - 1);
if (text.length() == 0) {
//如果文本没有了内容,则初始化计算器的各种值
resultText.setText("0");
firstDigit = true;
operator = "=";
} else {
//显示新的文本
resultText.setText(text);
}
}
}
/**
* 处理数字键被按下的事件
* @param key
*/
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 = "=";
}
/**
* 处理运算符键被按下的事件
* @param key
*/
private void handleOperator(String key) {
if (operator.equals("/")) {
//除法运算
//如果当前结果文本框中的值等于0
if (getNumberFromText() == 0.0){
//操作不合法
operateValidFlag = false;
resultText.setText("除数不能为零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("1/x")) {
//倒数运算
if (resultNum == 0.0){
//操作不合法
operateValidFlag = false;
resultText.setText("零没有倒数");
} else {
resultNum = 1 / resultNum;
}
} else if (operator.equals("+")){
//加法运算
resultNum += getNumberFromText();
} else if (operator.equals("-")){
//减法运算
resultNum -= getNumberFromText();
} else if (operator.equals("*")){
//乘法运算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
//平方根运算
resultNum = Math.sqrt(resultNum);
} else if (operator.equals("%")){
//百分号运算,除以100
resultNum = resultNum / 100;
} else if (operator.equals("+/-")){
//正数负数运算
resultNum = resultNum * (-1);
} 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;
}
/**
* 从结果文本框中获取数字
* @return
*/
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.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//定义JsqFrame继承Frame
class JsqFrame extends Frame {
double d1, d2; //定义两个double类型的变量
int op = -1; //定义两个int类型的变量
static TextField tf;//定义静态对象TextField
CalPanelL p1; //定义CalPanelL对象
// Constructor构造方法
JsqFrame() {
//以下设置属性
super("计算器");
setLayout(new FlowLayout());
setResizable(false);
setSize(250, 250);
tf = new TextField(18);
tf.setEditable(false);
tf.setBackground(Color.lightGray);
tf.setForeground(Color.red);
tf.setFont(new Font("Arial", Font.BOLD, 16));
add(tf);
p1 = new CalPanelL();
add(p1);
setVisible(true);
// addWindowListener(new Wclose());
}
//添加按钮继承Button类
class CalButton extends Button {
CalButton(String s) {
//设置按钮属性
super(s);
setBackground(Color.WHITE); //设置颜色为白色
}
}
//定义显示器继承Panel类
class CalPanelL extends Panel {
CalButton a, c, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bPN, bPoint,
bAdd, bSub, bMul, bDiv, bL, bR, bLn, bEqual, bCE, bQuit;
CalPanelL() {
//设置显示器的属性
setLayout(new GridLayout(6, 4));
setFont(new Font("TimesRoman", Font.BOLD, 16));
a = new CalButton("");
c = new CalButton("");
b0 = new CalButton("0");
b1 = new CalButton("1");
b2 = new CalButton("2");
b3 = new CalButton("3");
b4 = new CalButton("4");
b5 = new CalButton("5");
b6 = new CalButton("6");
b7 = new CalButton("7");
b8 = new CalButton("8");
b9 = new CalButton("9");
bPN = new CalButton("+/-");
bPoint = new CalButton(".");
// 设置按钮
bAdd = new CalButton("+");
bSub = new CalButton("-");
bMul = new CalButton("*");
bDiv = new CalButton("/");
bL = new CalButton("(");
bR = new CalButton(")");
bLn = new CalButton("ln");
bEqual = new CalButton("=");
bCE = new CalButton("CE");
bQuit = new CalButton("退出");
// 加入按钮
add(a);
add(c);
add(bCE);
bCE.addActionListener(new PressBCE());
add(bQuit);
bQuit.addActionListener(new PressBQuit());
add(b7);
b7.addActionListener(new PressB7());
add(b8);
b8.addActionListener(new PressB8());
add(b9);
b9.addActionListener(new PressB9());
add(bDiv);
bDiv.addActionListener(new PressBDiv());
add(b4);
b4.addActionListener(new PressB4());
add(b5);
b5.addActionListener(new PressB5());
add(b6);
b6.addActionListener(new PressB6());
add(bMul);
bMul.addActionListener(new PressBMul());
add(b1);
b1.addActionListener(new PressB1());
add(b2);
b2.addActionListener(new PressB2());
add(b3);
b3.addActionListener(new PressB3());
add(bSub);
bSub.addActionListener(new PressBSub());
add(b0);
b0.addActionListener(new PressB0());
add(bPoint);
bPoint.addActionListener(new PressBPoint());
add(bPN);
bPN.addActionListener(new PressBPN());
;
add(bAdd);
bAdd.addActionListener(new PressBAdd());
add(bL);
bL.addActionListener(new PressBL());
add(bR);
bR.addActionListener(new PressBR());
add(bLn);
bLn.addActionListener(new PressBLn());
add(bEqual);
bEqual.addActionListener(new PressBEqual());
}
}
//定义PressBAdd实现ActionListener
//大体的意思是按计算机按键的时出发的时间,设置按键的监听[加号的监听事件]
class PressBAdd implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String d1 = tf.getText();
op = 0;
tf.setText(d1 + "+");
} catch (Exception ee) {
}
}
}
//定义PressBSub实现ActionListener
//大体的意思是按计算机按键的时出发的时间,设置按键的监听[减号的监听事件]
class PressBSub implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String d1 = tf.getText();
op = 1;
tf.setText(d1 + "-");
} catch (Exception ee) {
}
}
}
//定义PressBMul实现ActionListener
//大体的意思是按计算机按键的时出发的时间,设置按键的监听[乘号的监听事件]
class PressBMul implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String d1 = tf.getText();
op = 2;
tf.setText(d1 + "*");
} catch (Exception ee) {
}
}
}
//定义PressBDiv实现ActionListener
//大体的意思是按计算机按键的时出发的时间,设置按键的监听[除号的监听事件]
class PressBDiv implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String d1 = tf.getText();
op = 3;
tf.setText(d1 + "/");
} catch (Exception ee) {
}
}
}
//定义PressBL实现ActionListener
//大体的意思是按计算机按键的时出发的时间,设置按键的监听[向左键的监听事件]
class PressBL implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String d1 = tf.getText();
op = 3;
tf.setText(d1 + "(");
} catch (Exception ee) {
}
}
}
//定义PressBR实现ActionListener
//大体的意思是按计算机按键的时出发的时间,设置按键的监听[向右键的监听事件]
class PressBR implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String d1 = tf.getText();
op = 3;
tf.setText(d1 + ")");
} catch (Exception ee) {
}
}
}
//定义PressBEqual实现ActionListener
//大体的意思是按计算机按键的时出发的时间,设置按键的监听[等号的监听事件]
class PressBEqual implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
Jsq jsq = new Jsq();
String s = tf.getText();
System.out.println(s);
while (s.indexOf("(") + 1 0 s.indexOf(")") 0) {
String s1 = jsq.caculateHigh(s);
System.out.println(s1);
s = s1;
}
String str = jsq.cacluteMain(s);
System.out.println(str);
tf.setText(String.valueOf(str));
} catch (Exception ee) {
}
}
}
/*
* 批量写吧
* 以下是按1、2、3等等的监听事件
* 还有清零的等等监听事件
*/
class PressBLn implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
double x = Double.parseDouble(tf.getText());
double y;
y = Math.log10(x);
tf.setText(y + "");
} catch (Exception ee) {
}
}
}
class PressBCE implements ActionListener {
public void actionPerformed(ActionEvent e) {
tf.setText("");
}
}
class PressBPN implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String text = tf.getText();
if (text != "") {
if (text.charAt(0) == '-')
tf.setText(text.substring(1));
else if (text.charAt(0) = '0' text.charAt(0) = '9')
tf.setText("-" + text.substring(0));
else if (text.charAt(0) == '.')
tf.setText("-0" + text.substring(0));
}
} catch (Exception ee) {
}
}
}
class PressBPoint implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
if (text.lastIndexOf(".") == -1)
tf.setText(text + ".");
}
}
class PressB0 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "0");
}
}
class PressB1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "1");
}
}
class PressB2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "2");
}
}
class PressB3 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "3");
}
}
class PressB4 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "4");
}
}
class PressB5 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "5");
}
}
class PressB6 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "6");
}
}
class PressB7 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "7");
}
}
class PressB8 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "8");
}
}
class PressB9 implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
tf.setText(text + "9");
}
}
class PressBQuit implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public void Js() {
String text = tf.getText();
tf.setText(text);
}
}
求一个java 计算器,支持键盘输入的代码,最好有注释
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//while(true){
Scanner sc = new Scanner(System.in);
System.out.println(jisuan(sc.next()));
}
private static float jisuan(String cont){
List arryList = new ArrayList();
char[] str = cont.toCharArray();
Character astr;
String s = "";
for(int i=0;istr.length;i++){
astr = str[i];
if(astr=='+'||astr=='-'||astr=='*'||astr=='/'||astr=='=')
{
arryList.add(s);
s="";
if(astr!='='){
arryList.add(astr.toString());
}
}else{
s += astr;
}
}
float count = 0;
List jjlist = chengchuModel(arryList);
String ssf = "";
String var1 = "";
String var2 = "";
if(jjlist.size()=3){
for(int i=1;ijjlist.size();i=i+2){ //jjlist中就只有加减法了
ssf = (String)jjlist.get(i); // 获得jjlist中的加法或减法字符进行判断
var2 = (String)jjlist.get(i+1);
if(i==1){ //判断第一个运算符是加号还是减号,两个情况下的运行也是不同的
var1 = (String)jjlist.get(i-1); //只有第一次加减的时候才会去取前一个数字进行运算
if(ssf.trim().equals("-")){
count = Float.parseFloat(var1) - Float.parseFloat(var2);
}else{
count = Float.parseFloat(var1) + Float.parseFloat(var2);
}
}else{
if(ssf.trim().equals("-")){
count = count - Float.parseFloat(var2);
}else{
count = count + Float.parseFloat(var2);
}
}
}
}else{
count = Float.parseFloat(jjlist.get(0).toString());
}
return count;
}
private static boolean checkstr(String str){
if(!str.trim().equals("*")!str.trim().equals("/"))
return true;
return false;
}
private static boolean cheng(String str){
if(str.trim().equals("*"))
return true;
return false;
}
private static boolean chu(String str){
if(str.trim().equals("/"))
return true;
return false;
}
private static List chengchuModel(List list){ //将输入的算术的所有乘除法算出来只剩下加减法
String var1 ="";
String var2 ="";
String var3 ="";
for(int i=1;ilist.size();i=i+2){
var1 = (String)list.get(i-1);
var2 = (String)list.get(i);
var3 = (String)list.get(i+1);
if(!checkstr(var2)){
if(cheng(var2)){
list.set(i-1, String.valueOf((Float.parseFloat(var1)*Float.parseFloat(var3))));
list.remove(i);
list.remove(i);
i = i-2;
//
}else if(chu(var2)){
list.set(i-1, String.valueOf((Float.parseFloat(var1)/Float.parseFloat(var3))));
list.remove(i);
list.remove(i);
i = i-2;
}
}
}
return list;
}
}
测试:
输入:33-6*5+7/4=
结果:4.75
求一个java计算器程序 要注释!
package CalcTest;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import org.w3c.dom.Text;
import com.sun.org.apache.bcel.internal.generic.JsrInstruction;
public class Calc extends JFrame implements ActionListener{
public final int max = 8;//定义文本框最多输入字符
String copy;
boolean enter;
int key = -1,prekey = -1;
double vard,answerd;
String curDate="";
Double opate1 = 0.0;
Double opate2 = 0.0;
DecimalFormat df;
JPanel ButtonPanel,okPanel;
JButton jb[];
JTextField jtf;
JScrollPane jsp;
JButton jia,jian,cheng,chu,dian,dengyu;
JMenuBar jmb;
JMenu bjM,ckM,bzM;
JTextArea jta;
JMenuItem copyM,pasteM,closeM,helpM,gyM;
JButton b1;
boolean start;
public Calc(){
enter = true;
start =true;
df = new DecimalFormat("0.#########");
Container c = getContentPane();
//**以下为菜单之类的
jmb = new JMenuBar();
bjM = new JMenu("编辑(E)");
ckM = new JMenu("查看(V)");
bzM = new JMenu("帮助(H)");
copyM = new JMenuItem("复制(C)");
pasteM = new JMenuItem("粘贴(V)");
closeM = new JMenuItem("关闭(E)");
helpM = new JMenuItem("帮助主题");
gyM = new JMenuItem("关于计算器");
jmb.add(bjM);
jmb.add(ckM);
jmb.add(bzM);
bjM.add(copyM);
bjM.add(pasteM);
ckM.add(closeM);
bzM.add(helpM);
bzM.add(gyM);
setJMenuBar(jmb);//显示菜单条
//**以上为菜单类的
//**以下注册菜单监听器
copyM.addActionListener(this);
pasteM.addActionListener(this);
closeM.addActionListener(this);
helpM.addActionListener(this);
gyM.addActionListener(this);
//**以上注册菜单监听器
jtf = new JTextField(35);
jtf.setText("0.");
jtf.setEditable(false);
//jtf.setComponentOrientation(java.awt.ComponentOrientation.RIGHT_TO_LEFT);//设置文本框从右往左
jtf.setHorizontalAlignment(JTextField.RIGHT);//跟上面效果一样
jtf.setText("");//设置每次都重新获取
//**以下为按钮设置
jb = new JButton[10];
jia = new JButton("+");
jian = new JButton("-");
cheng = new JButton("*");
chu = new JButton("\\");
dian = new JButton(".");
dengyu = new JButton("=");
jia.addActionListener(this);
jian.addActionListener(this);
cheng.addActionListener(this);
chu.addActionListener(this);
dian.addActionListener(this);
dengyu.addActionListener(this);
ButtonPanel = new JPanel();
for(int i=0;ijb.length;i++){
jb[i] = new JButton(Integer.toString(i));//实现将整形转字符串
jb[i].setForeground(new Color(99,00,00));
jb[i].addActionListener(Calc.this);//为每个按钮注册监听器
}
ButtonPanel.setLayout(new GridLayout(4,4));//设置格子布局4行4列
ButtonPanel.add(jb[1]);
ButtonPanel.add(jb[2]);
ButtonPanel.add(jb[3]);
ButtonPanel.add(jia);
ButtonPanel.add(jb[4]);
ButtonPanel.add(jb[5]);
ButtonPanel.add(jb[6]);
ButtonPanel.add(jian);
ButtonPanel.add(jb[7]);
ButtonPanel.add(jb[8]);
ButtonPanel.add(jb[9]);
ButtonPanel.add(cheng);
ButtonPanel.add(jb[0]);
ButtonPanel.add(dian);
ButtonPanel.add(dengyu);
ButtonPanel.add(chu);
//**以上为按钮设置
//**以下为帮助主题
jta = new JTextArea(5,10);
jsp = new JScrollPane(jta);
jta.setEditable(false);
jta.setFont(new Font("楷体",Font.BOLD,20));
jta.append("执行简单计算\n");
jta.append("1. 键入计算的第一个数字。\n");
jta.append("2. 单击“+”执行加、“-”执行减、“*”执行乘或“/”执行除。\n");
jta.append("3. 键入计算的下一个数字。\n");
jta.append("4. 输入所有剩余的运算符和数字。\n");
jta.append("5. 单击“=”。\n");
//**以上为帮助主题
//**以下为清零
okPanel = new JPanel();
b1 = new JButton("C");
okPanel.add(b1);
//**以上为清零
b1.addActionListener(this);//注册监听器
c.add(jtf,BorderLayout.NORTH);
c.add(ButtonPanel,BorderLayout.CENTER);
c.add(okPanel,BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
Object temp = e.getSource();
if(temp == dian enter == true){
boolean isDot = false;
if(jtf.getText().length()==0)
isDot=true;
for(int i = 0;ijtf.getText().length();i++){
if('.'== jtf.getText().charAt(i)){
System.out.println(i);
isDot = true;
break;
}
}
if(isDot==false)
jtf.setText(jtf.getText() + ".");
}
if(jtf.getText().length()==max){
jtf.setText("输入超出最大长度");
enter=false;
}
if((temp == jia || temp == jian || temp == cheng || temp ==chu) enter == true){
if(temp == jia){
switch (prekey) {
case 0:
answerd += Double.parseDouble(jtf.getText());//将String值转换成DOUBLE,返回一个新的double值
break;
case 1:
answerd -= Double.parseDouble(jtf.getText());
case 2:
answerd *= Double.parseDouble(jtf.getText());
case 3:
if (Double.parseDouble(jtf.getText()) == 0) {
jtf.setText("除数不能为零");
enter = false;
}
else
answerd /= Double.parseDouble(jtf.getText());
break;
default:
answerd = Double.parseDouble(jtf.getText());
System.out.println(answerd);
break;
}
jtf.setText("");
prekey = key = 0;
}
if(temp==jian){
switch (prekey) {
case 0:
answerd += Double.parseDouble(jtf.getText());
break;
case 1:
answerd -= Double.parseDouble(jtf.getText());
case 2:
answerd *= Double.parseDouble(jtf.getText());
case 3:
if (Double.parseDouble(jtf.getText()) == 0) {
jtf.setText("除数不能为零");
enter = false;
}
else
answerd /= Double.parseDouble(jtf.getText());
break;
default:
answerd = Double.parseDouble(jtf.getText());
break;
}
jtf.setText("");
prekey = key = 1;
}
if(temp==cheng){
switch (prekey) {
case 0:
answerd += Double.parseDouble(jtf.getText());
break;
case 1:
answerd -= Double.parseDouble(jtf.getText());
case 2:
answerd *= Double.parseDouble(jtf.getText());
case 3:
if (Double.parseDouble(jtf.getText()) == 0) {
jtf.setText("除数不能为零");
enter = false;
}
else
answerd /= Double.parseDouble(jtf.getText());
break;
default:
answerd = Double.parseDouble(jtf.getText());
break;
}
jtf.setText("");
prekey = key = 2;
}
if(temp==chu){
switch (prekey) {
case 0:
answerd += Double.parseDouble(jtf.getText());
break;
case 1:
answerd -= Double.parseDouble(jtf.getText());
case 2:
answerd *= Double.parseDouble(jtf.getText());
case 3:
if (Double.parseDouble(jtf.getText()) == 0) {
jtf.setText("除数不能为零");
enter = false;
}
else
answerd /= Double.parseDouble(jtf.getText());
break;
default:
answerd = Double.parseDouble(jtf.getText());
break;
}
jtf.setText("");
prekey = key = 3;
}
}
if(temp==dengyu enter==true){
if(prekey==5){
if(key==0){
answerd += vard;
jtf.setText(df.format(answerd));// 格式化一个 double 值,以生成一个字符串。
}
if(key==1){
answerd -= vard;
jtf.setText(df.format(answerd));
}
if(key==2){
answerd *= vard;
jtf.setText(df.format(answerd));
}
if(key==3){
if(Double.parseDouble(jtf.getText())==0){
jtf.setText("除数不能为0");
enter = false;
}else {
answerd /= vard;
jtf.setText(df.format(answerd));
}
}
}else {
vard = Double.parseDouble(jtf.getText());
System.out.println(vard);
if(key==0){
prekey = -1;
answerd += Double.parseDouble(jtf.getText());
jtf.setText(df.format(answerd));
}
if(key==1){
prekey = -1;
answerd -= Double.parseDouble(jtf.getText());
jtf.setText(df.format(answerd));
}
if(key==2){
prekey = -1;
answerd *= Double.parseDouble(jtf.getText());
jtf.setText(df.format(answerd));
}
if(key==3){
prekey = -1;
if(Double.parseDouble(jtf.getText())==0){
jtf.setText("除数不能为0");
enter = false;
}else {
answerd /= Double.parseDouble(jtf.getText());
jtf.setText(df.format(answerd));
}
}
}
prekey=5;
}
if(temp==b1){
jtf.setText("");
enter=true;
}
//将按钮挨个转换为字符串
for(int i=0;ijb.length;i++){
if(temp==jb[i] enter==true){
jtf.setText(jtf.getText() + Integer.toString(i));
}
}
//**以下为MemuItem进行事件
if(temp==copyM){
copy = jtf.getText();
}
if(temp==pasteM){
jtf.setText(copy);
}
if(temp==closeM){
dispose();
System.exit(0);
}
if(temp==gyM){
//JOptionPane.showMessageDialog(gyM,jsp);
JOptionPane.showMessageDialog(gyM, jsp);
}
if(temp == helpM){
JOptionPane.showMessageDialog(helpM,"使用“计算器”可以完成任意的通常借助手持计算器来完成的标准运算。 \n “计算器”可用于基本的算术运算,比如加减运算等。 \n 同时它还具有科学计算器的功能,比如对数运算和阶乘运算等。");
}
//**以上为MemuItem进行事件
}
public static void main(String[] args) {
Calc cc = new Calc();
cc.setTitle("计算器 v1.0");
cc.setSize(400, 400);
cc.setBounds(300, 300, 300, 300);
cc.setVisible(true);
}
}
谁能给一个Java的计算器程序代码(加注释 )
以前写的,给你了
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator {
//计算器面板
private JFrame f = new JFrame("Calculator");
//输入面扳
private JPanel inputPanel = new JPanel();
//加减乘除面板
private JPanel operationPanel = new JPanel();
//数字面板
private JPanel buttonsPanel = new JPanel();
//输入数据文本框
private JTextField input = new JTextField(20);
//退格键
private JButton backspace = new JButton("BackSpace");
//清空
private JButton CE = new JButton("CE ");
//删除
private JButton C = new JButton("C ");
//四则运算符号键
private JButton add = new JButton("+");
private JButton sub = new JButton("-");
private JButton mul = new JButton("*");
private JButton div = new JButton("/");
//小数点
private JButton decimal = new JButton(".");
//等号
private JButton equal = new JButton("=");
//数字键
private JButton zero = new JButton("0");
private JButton one = new JButton("1");
private JButton two = new JButton("2");
private JButton three = new JButton("3");
private JButton four = new JButton("4");
private JButton five = new JButton("5");
private JButton six = new JButton("6");
private JButton seven = new JButton("7");
private JButton eight = new JButton("8");
private JButton nine = new JButton("9");
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);
operationPanel.add(backspace);
operationPanel.add(CE);
operationPanel.add(C);
f.add(operationPanel, BorderLayout.CENTER);
buttonsPanel.add(add);
buttonsPanel.add(sub);
buttonsPanel.add(mul);
buttonsPanel.add(div);
buttonsPanel.add(one);
buttonsPanel.add(two);
buttonsPanel.add(three);
buttonsPanel.add(zero);
buttonsPanel.add(four);
buttonsPanel.add(five);
buttonsPanel.add(six);
buttonsPanel.add(decimal);
buttonsPanel.add(seven);
buttonsPanel.add(eight);
buttonsPanel.add(nine);
buttonsPanel.add(equal);
buttonsPanel.setLayout(new GridLayout(4, 4));
f.add(buttonsPanel, BorderLayout.SOUTH);
//注册各个组件监听事件
backspace.addMouseListener(new OperationMouseListener());
CE.addMouseListener(new OperationMouseListener());
C.addMouseListener(new OperationMouseListener());
decimal.addMouseListener(new OperationMouseListener());
equal.addMouseListener(new OperationMouseListener());
//注册四则运算监听
add.addMouseListener(new CalcMouseListener());
sub.addMouseListener(new CalcMouseListener());
mul.addMouseListener(new CalcMouseListener());
div.addMouseListener(new CalcMouseListener());
//注册数字监听事件
zero.addMouseListener(new NumberMouseListener());
one.addMouseListener(new NumberMouseListener());
two.addMouseListener(new NumberMouseListener());
three.addMouseListener(new NumberMouseListener());
four.addMouseListener(new NumberMouseListener());
five.addMouseListener(new NumberMouseListener());
six.addMouseListener(new NumberMouseListener());
seven.addMouseListener(new NumberMouseListener());
eight.addMouseListener(new NumberMouseListener());
nine.addMouseListener(new NumberMouseListener());
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class NumberMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(input.getText().trim().equals("0")){//如果文本框已经是0,结果还是0
input.setText(((JButton)e.getSource()).getText().trim());
}else{//否则的话,把0添加到后面,譬如文本框是1,结果就为10
input.setText(input.getText().concat(((JButton)e.getSource()).getText().trim()));
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class CalcMouseListener implements MouseListener{
//如果输入的是运算符号,保存第一个结果和运算符号
public void mouseClicked(MouseEvent e) {
num1 = input.getText().trim();input.setText("");
operator = ((JButton)e.getSource()).getText().trim();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class OperationMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(e.getSource() == backspace){//退格键,删除一个直到没有字符删除
String inputText = input.getText();
if(inputText.length() 0){
input.setText(inputText.substring(0, inputText.length() - 1));
}
}else if(e.getSource() == C){
input.setText("0");//C,清空所有运算数字和符号
num1 = "";
}else if(e.getSource() == CE){
input.setText("0");//CE--将文本框置为0
}else if(e.getSource() == decimal){
String text = input.getText().trim();
//如果按了小数点,如果文本框已经有小数点,不做任何操作,否则在结果后面加上小数点
if(text.indexOf(".") == -1){
input.setText(text.concat("."));
}
}else if(e.getSource() == equal){
//如果是等号
if(!operator.trim().equals("")){
if(!input.getText().trim().equals("")){
double result = 0D;
if(operator.equals("+")){//执行加法运算
result = Double.parseDouble(num1) + Double.parseDouble(input.getText().trim());
}else if(operator.equals("-")){//减法运算
result = Double.parseDouble(num1) - Double.parseDouble(input.getText().trim());
}else if(operator.equals("*")){//乘法运算
result = Double.parseDouble(num1) * Double.parseDouble(input.getText().trim());
}else if(operator.equals("/")){//除法运算
result = Double.parseDouble(num1) / Double.parseDouble(input.getText().trim());
}
//格式化最终结果,保留两位小数点
input.setText(new DecimalFormat("0.00").format(result));
}
}
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
}
分享题目:java计算器代码带注释 java计算器代码解析
网页网址:http://scyanting.com/article/dooeogg.html