读书人

急需java计算器小程序

发布时间: 2012-01-08 22:48:50 作者: rapoo

急需java计算器小程序,在线等!!!!!!!
小弟对java了解有限,现在急需一个简单的计算器的小程序,不需要用户界面,在命令行底下执行就可以了,只要做到简单的加减乘除即可,括号运算也不需要.
要求:
1,四则运算
2,输入等号"="后得出结果
3,运算的数字个数不限,直到输入等号为止

本来是一个非常简单的程序,因为急用,所以请各位大虾帮忙。

[解决办法]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
class Test extends Applet implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b1,b2,b3,b4;
public void init()
{
l1=new Label( "操作数 ");
l2=new Label( "被操作数 ");
l3=new Label( "结果 ");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
b1=new Button( "加 ");
b2=new Button( "减 ");
b3=new Button( "乘 ");
b4=new Button( "除 ");
add(b1);add(b2);add(b3);add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent j)
{
double n;
try{
if(j.getSource()==b1)
{
double n1,n2;
n1=Double.parseDouble(t1.getText());
n2=Double.parseDouble(t2.getText());
n=n1+n2;
t3.setText(String.valueOf(n));
}
if(j.getSource()==b2)
{
double n1,n2;
n1=Double.parseDouble(t1.getText());
n2=Double.parseDouble(t2.getText());
n=n1-n2;
t3.setText(String.valueOf(n));
}
if(j.getSource()==b3)
{
double n1,n2;
n1=Double.parseDouble(t1.getText());
n2=Double.parseDouble(t2.getText());
n=n1*n2;
t3.setText(String.valueOf(n));
}
if(j.getSource()==b4)
{
double n1,n2;
n1=Double.parseDouble(t1.getText());
n2=Double.parseDouble(t2.getText());
n=n1/n2;
t3.setText(String.valueOf(n));
}
}catch(Exception e){}
}
}
不太明白LZ的意思,一个小程序,applet吗?在命令行执行,从键盘输入吗?写了个applet的.
[解决办法]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator
{
public static void main(String[] args)
{
CalculatorFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

/**
A frame with a calculator panel.
*/
class CalculatorFrame extends JFrame
{
public CalculatorFrame()
{
setTitle( "Calculator ");
CalculatorPanel panel = new CalculatorPanel();
add(panel);
pack();
}
}

/**
A panel with calculator buttons and a result display.
*/
class CalculatorPanel extends JPanel
{
public CalculatorPanel()
{
setLayout(new BorderLayout());

result = 0;
lastCommand = "= ";
start = true;

// add the display

display = new JButton( "0 ");
display.setEnabled(false);


add(display, BorderLayout.NORTH);

ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();

// add the buttons in a 4 x 4 grid

panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));

addButton( "7 ", insert);
addButton( "8 ", insert);
addButton( "9 ", insert);
addButton( "/ ", command);

addButton( "4 ", insert);
addButton( "5 ", insert);
addButton( "6 ", insert);
addButton( "* ", command);

addButton( "1 ", insert);
addButton( "2 ", insert);
addButton( "3 ", insert);
addButton( "- ", command);

addButton( "0 ", insert);
addButton( ". ", insert);
addButton( "= ", command);
addButton( "+ ", command);

add(panel, BorderLayout.CENTER);
}

/**
Adds a button to the center panel.
@param label the button label
@param listener the button listener
*/
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}

/**
This action inserts the button action string to the
end of the display text.
*/
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
if (start)
{
display.setText( " ");
start = false;
}
display.setText(display.getText() + input);
}
}

/**
This action executes the command that the button
action string denotes.
*/
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();

if (start)
{
if (command.equals( "- "))
{
display.setText(command);
start = false;
}
else
lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}
}
}

/**
Carries out the pending calculation.
@param x the value to be accumulated with the prior result.
*/
public void calculate(double x)
{
if (lastCommand.equals( "+ ")) result += x;
else if (lastCommand.equals( "- ")) result -= x;
else if (lastCommand.equals( "* ")) result *= x;
else if (lastCommand.equals( "/ ")) result /= x;
else if (lastCommand.equals( "= ")) result = x;
display.setText( " " + result);
}

private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}

[解决办法]
是不是这样:
class Jis
{
public static void main(String[] args)


{
int num1,num2;
int n;
char op= 's ';
num1=Integer.parseInt(args[0]);
num2=Integer.parseInt(args[2]);
op=args[1].charAt(0);
switch(op)
{
case '+ ':
n=num1+num2;
System.out.print( " "+num1+ "+ "+num2+ "= "+n);
break;
case '- ':
n=num1-num2;
System.out.print( " "+num1+ "- "+num2+ "= "+n);
break;
case '/ ':
n=num1/num2;
System.out.print( " "+num1+ "/ "+num2+ "= "+n);
break;
case 'x ':
n=num1*num2;
System.out.print( " "+num1+ "* "+num2+ "= "+n);
break;
}
}
}
[解决办法]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
private boolean dotExist, operated, equaled; // 帮助运算的布尔变量
private double storedNumber; // 目前的结果
private char lastOperator; // 表示上一运算符
private JTextField operation; // 结果栏
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear; // 运算符
private JButton[] numbers; // 数字
// 构造者
public Calculator()
{
setTitle( "Calculator ");
// 初始化变量
dotExist = false; // 表示当前的数是否有小数点
operated = false; // 表示任意运算符是否被按下
equaled = false; // 表示等号是否被按下
storedNumber = 0;
lastOperator = '? ';
// 初始化窗口变量
operation = new JTextField( "0 ");
operation.setEditable(false);
numbers = new JButton[10];
for (int i = 0; i < 10; i++)
numbers[i] = new JButton( " " + i);
dot = new JButton( ". ");
plus = new JButton( "+ ");
minus = new JButton( "- ");
multi = new JButton( "* ");
div = new JButton( "/ ");
sqrt = new JButton( "√ ");
equal = new JButton( "= ");
changePN = new JButton( "± ");
clear = new JButton( "AC ");
// 将窗口物体放入窗口
GridBagLayout layout = new GridBagLayout();
getContentPane().setLayout(layout);
addComponent(layout, operation, 0, 0, 4, 1);
addComponent(layout, numbers[1], 1, 0, 1, 1);
addComponent(layout, numbers[2], 1, 1, 1, 1);
addComponent(layout, numbers[3], 1, 2, 1, 1);
addComponent(layout, numbers[4], 2, 0, 1, 1);
addComponent(layout, numbers[5], 2, 1, 1, 1);
addComponent(layout, numbers[6], 2, 2, 1, 1);
addComponent(layout, numbers[7], 3, 0, 1, 1);
addComponent(layout, numbers[8], 3, 1, 1, 1);
addComponent(layout, numbers[9], 3, 2, 1, 1);
addComponent(layout, dot, 4, 0, 1, 1);
addComponent(layout, numbers[0], 4, 1, 1, 1);
addComponent(layout, sqrt, 4, 2, 1, 1);
addComponent(layout, plus, 1, 3, 1, 1);
addComponent(layout, minus, 2, 3, 1, 1);
addComponent(layout, multi, 3, 3, 1, 1);
addComponent(layout, div, 4, 3, 1, 1);
addComponent(layout, equal, 5, 0, 2, 1);
addComponent(layout, changePN, 5, 2, 1, 1);
addComponent(layout, clear, 5, 3, 1, 1);
}
// 对按钮进行反应的方法
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
if (btn == clear)
{
operation.setText( "0 ");
dotExist = false;
storedNumber = 0;
lastOperator = '? ';
}
else if (btn == equal)
{
operate( '= ');
equaled = true;
}
else if (btn == plus)
{
operate( '+ ');
equaled = false;


}
else if (btn == minus)
{
operate( '- ');
equaled = false;
}
else if (btn == multi)
{
operate( '* ');
equaled = false;
}
else if (btn == div)
{
operate( '/ ');
equaled = false;
}
else if (btn == changePN)
{
operate( 'p ');
operate( '= ');
equaled = true;
}
else if (btn == sqrt)
{
operate( 's ');
operate( '= ');
equaled = true;
}
else
{
if (equaled)
storedNumber = 0;
for (int i = 0; i < 10; i++)
if (btn == numbers[i])
{
if (operation.getText().equals( "0 "))
operation.setText( " " + i);
else if(! operated)
operation.setText(operation.getText() + i);
else
{
operation.setText( " " + i);
operated = false;
}
}
if (btn == dot && ! dotExist)
{
operation.setText(operation.getText() + ". ");
dotExist = true;
}
}
}
// 进行运算的方法
private void operate(char operator)
{
double currentNumber = Double.valueOf(operation.getText()).doubleValue();
if (lastOperator == '? ')
storedNumber = currentNumber;
else if (lastOperator == '+ ')
storedNumber += currentNumber;
else if (lastOperator == '- ')
storedNumber -= currentNumber;
else if (lastOperator == '* ')
storedNumber *= currentNumber;
else if (lastOperator == '/ ')
storedNumber /= currentNumber;
else if (lastOperator == 'p ')
storedNumber *= -1;
else if (lastOperator == 's ')
storedNumber = Math.sqrt(currentNumber);
else if (lastOperator == '= ' && equaled)
storedNumber = currentNumber;
operation.setText( " " + storedNumber);
operated = true;
lastOperator = operator;
}
// 快捷使用GridBagLayout的方法
private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height)
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(10, 2, 10, 2);
constraints.weightx = 100;
constraints.weighty = 100;
constraints.gridx = col;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
if (component instanceof JButton)
((JButton)component).addActionListener(this);
getContentPane().add(component);
}
// 主方法初始化并显示窗口
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setSize(290, 400);
calc.setVisible(true);
}
}
[解决办法]
楼主都说了不要Applet了,大家要遵守需求哦~我自己写了一个,用了3小时...有点麻烦,似乎可以简化,不过能用,控制台录入表达式,支持小数加减乘除,不支持括号.

/*
* Created on 2007-7-12
*/
package willishz.soho.arithmetic;

import java.util.ArrayList;
import java.util.Scanner;

/**
* calculate an expression(end with "= ", decimal supported, brackets unsupported).
* @author willishz
*/
public class ExpressionCalculator {

public static final char PLUS = '+ ';
public static final char SUBTRACT = '- ';
public static final char MULTIPLE = '* ';
public static final char DIVIDE = '/ ';
public static final char DECIMAL = '. ';
public static final char EQUAL = '= ';



public static final String PLUS_STR = "+ ";
public static final String SUBTRACT_STR = "- ";
public static final String MULTIPLE_STR = "* ";
public static final String DIVIDE_STR = "/ ";

/**
* interpret expression string to units.
* @param expression
* @return
*/
public static String interpret(String expression) {
ArrayList explist = new ArrayList();
int flg = 0; // flag to divide expression units
StringBuffer sb = new StringBuffer();
char[] expChars = expression.toCharArray();
// expression string to units
for (int i = 0; i < expChars.length; i++) {
// expression divided by operators
if (expChars[i] == ExpressionCalculator.EQUAL || expChars[i] == ExpressionCalculator.PLUS || expChars[i] == ExpressionCalculator.SUBTRACT || expChars[i] == ExpressionCalculator.MULTIPLE || expChars[i] == ExpressionCalculator.DIVIDE) {
// paste digits of number between each two segments
for (int j = flg; j < i; j++) {
sb.append(expChars[j]);
flg = i + 1;
}
// sucess divide a unit
explist.add(sb.toString());
// expression end with "= ", paste last digits of number
if (expChars[i] != ExpressionCalculator.EQUAL) {
explist.add(String.valueOf(expChars[i]));
}
sb = new StringBuffer();
}
}
// calculate this expression units
return ExpressionCalculator.calculate(explist);
}

/**
* calculate all units.
* @param explist
* @return
*/
public static String calculate(ArrayList explist) {
do {
int operatorIndex = -1; // operator location
// count operator, first multiple and divide
if (explist.indexOf(ExpressionCalculator.PLUS_STR) > 0 && explist.indexOf(ExpressionCalculator.DIVIDE_STR) > 0) { // both
operatorIndex = Math.min(explist.indexOf(ExpressionCalculator.PLUS_STR), explist.indexOf(ExpressionCalculator.DIVIDE_STR));
} else if ((explist.indexOf(ExpressionCalculator.PLUS_STR) > 0 && explist.indexOf(ExpressionCalculator.DIVIDE_STR) < 0)) { // multiple only
operatorIndex = explist.indexOf(ExpressionCalculator.PLUS_STR);
} else if ((explist.indexOf(ExpressionCalculator.PLUS_STR) < 0 && explist.indexOf(ExpressionCalculator.DIVIDE_STR) > 0)) { // divide only
operatorIndex = explist.indexOf(ExpressionCalculator.DIVIDE_STR);
}

// finish counting multiple or divide operator
if (operatorIndex > 0) { // do have multiple or divide operator
explist = execute(explist, operatorIndex); // multiple or divide operation
continue; // continue calculate
}

// no multiple or divide operation, count plus and subtract operator
if (explist.indexOf(ExpressionCalculator.PLUS_STR) > 0 && explist.indexOf(ExpressionCalculator.SUBTRACT_STR) > 0) { // both
operatorIndex = Math.min(explist.indexOf(ExpressionCalculator.PLUS_STR), explist.indexOf(ExpressionCalculator.SUBTRACT_STR));
} else if ((explist.indexOf(ExpressionCalculator.PLUS_STR) > 0 && explist.indexOf(ExpressionCalculator.SUBTRACT_STR) < 0)) { // plus only
operatorIndex = explist.indexOf(ExpressionCalculator.PLUS_STR);


} else if ((explist.indexOf(ExpressionCalculator.PLUS_STR) < 0 && explist.indexOf(ExpressionCalculator.SUBTRACT_STR) > 0)) { // substract only
operatorIndex = explist.indexOf(ExpressionCalculator.SUBTRACT_STR);
}

// finish counting plus or subtract operator
if (operatorIndex > 0) { // do have plus or subtract operator
explist = execute(explist, operatorIndex); // plus or subtract operation
continue; // continue calculate
}

// no operators
return explist.get(0).toString(); // return result
} while(true);
}

/**
* calculate two units.
* @param explist
* @return
*/
public static ArrayList execute(ArrayList explist, int operatorIndex) {
double unit1 = Double.valueOf(explist.get(operatorIndex - 1).toString()).doubleValue(); // get factor1
double unit2 = Double.valueOf(explist.get(operatorIndex + 1).toString()).doubleValue(); // get factor2
char operator = explist.get(operatorIndex).toString().charAt(0); // get operator
// estimate operator, do calculate, then rebuild arraylist
switch (operator) {
case ExpressionCalculator.PLUS:
explist.set(operatorIndex - 1, String.valueOf(unit1 + unit2));
explist.remove(operatorIndex + 1);
explist.remove(operatorIndex);
break;
case ExpressionCalculator.SUBTRACT:
explist.set(operatorIndex - 1, String.valueOf(unit1 - unit2));
explist.remove(operatorIndex + 1);
explist.remove(operatorIndex );
break;
case ExpressionCalculator.MULTIPLE:
explist.set(operatorIndex - 1, String.valueOf(unit1 * unit2));
explist.remove(operatorIndex + 1);
explist.remove(operatorIndex);
break;
case ExpressionCalculator.DIVIDE:
explist.set(operatorIndex - 1, String.valueOf(unit1 / unit2));
explist.remove(operatorIndex + 1);
explist.remove(operatorIndex);
break;
}
return explist;
}

public static void main(String[] args) {
System.out.print( "请输入一个表达式以 \ "=\ " 结束(中间不加空格, 支持小数, 不支持括号): ");
Scanner sc = new Scanner(System.in); // from console
System.out.println(ExpressionCalculator.interpret(sc.next()));
System.exit(0);
}
}

读书人网 >J2SE开发

热点推荐