小弟对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);