import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Counter extends WindowAdapter
{
static JFrame f=new JFrame("計算器");
static JTextField text1=new JTextField("0.");
static String source="";
static String cal="";
static String object="";
static boolean flag=false;
static boolean flag1=true;
static boolean flag2=false;
public void init()
{
try
{
Container c=f.getContentPane();
JPanel pan1=new JPanel();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
JButton b0=new JButton("0");
JButton b11=new JButton("+");
JButton b12=new JButton("-");
JButton b13=new JButton("*");
JButton b14=new JButton("/");
JButton b15=new JButton(".");
JButton b16=new JButton("=");
JButton bclar=new JButton("清零");
text1.setHorizontalAlignment(JTextField.RIGHT);
c.add(text1,"North");
c.add(pan1);
A aa=new A();
Result re=new Result();
Opertion op=new Opertion();
Clar cl=new Clar();
b1.addActionListener(aa);
b2.addActionListener(aa);
b3.addActionListener(aa);
b4.addActionListener(aa);
b5.addActionListener(aa);
b6.addActionListener(aa);
b7.addActionListener(aa);
b8.addActionListener(aa);
b9.addActionListener(aa);
b0.addActionListener(aa);
b11.addActionListener(op);
b12.addActionListener(op);
b13.addActionListener(op);
b14.addActionListener(op);
b16.addActionListener(re);
b15.addActionListener(aa);
bclar.addActionListener(cl);
pan1.add(b1);
pan1.add(b2);
pan1.add(b3);
pan1.add(b11);
pan1.add(b4);
pan1.add(b5);
pan1.add(b6);
pan1.add(b12);
pan1.add(b7);
pan1.add(b8);
pan1.add(b9);
pan1.add(b13);
pan1.add(b0);
pan1.add(b15);
pan1.add(b16);
pan1.add(b14);
pan1.add(bclar);
f.setSize(200,220);
f.setVisible(true);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
class A implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String a=text1.getText();
String s=e.getActionCommand();
if(a.equals("0.")||a.equals("+")||a.equals("-")||a.equals("*")||a.equals("/"))
text1.setText(s);
else {
if(flag2)
{
text1.setText(s);
flag2=false;
}
else
text1.setText(a+s);
}
}
}
class Opertion implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
cal=e.getActionCommand();
if(flag1==true)
source=text1.getText();
text1.setText(cal);
flag1=false;
flag=true;
}
}
class Result implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double num1;
num1=Double.parseDouble(source);
object=text1.getText();
double num2;
num2=Double.parseDouble(object);
double result=0;
if(cal.equals("+"))
result=num1+num2;
if(cal.equals("-"))
result=num1-num2;
if(cal.equals("*"))
result=num1*num2;
if(cal.equals("/"))
if(num2==0)
text1.setText("除數不能為0");
else
result=num1/num2;
String s1=Double.toString(result);
text1.setText(s1);
flag1=true;
flag2=true;
}
}
class Clar implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
text1.setText("0.");
}
}
public static void main(String[] args)
{
Counter count=new Counter();
count.init();
}
public void windowClosing(WindowEvent e){
System.exit(1);
}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
}
2. 求計算器Java代碼。。。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
class JPanelEa1 extends JFrame implements MenuListener,ActionListener
{
JPanel mainp,p1,p2,p3,p4;
JTextField jt1;
JMenuItem mnuCopy;
JMenuItem mnuPaste;
JButton bM;
boolean isDouble = false;// 是否為實數
int opFlag = -1;
static double t1 = 0, t2 = 0, t3 = 0, result = 0;
static int opflag1 = -1, opflag2 = -1, flag = 0, resflag = 1;
int preOp, currentOp = 0;// 標准位
double op1 = 0, op2 = 0;// 操作數
double n3;
StringBuffer buf = new StringBuffer(20);
StringBuffer Board = new StringBuffer(20);// 剪貼板
StringBuffer memory = new StringBuffer(20);// M系列
StringBuffer str = new StringBuffer();
public JPanelEa1()
{
p1=new JPanel();
p1.setLayout(new GridLayout(2,1,10,10));
JMenuBar mnuNotepad=new JMenuBar();
JMenu mnuEdit=new JMenu("編輯(E)");
mnuEdit.setMnemonic(KeyEvent.VK_E);
JMenu mnuCheck=new JMenu("查看(V)");
mnuCheck.setMnemonic(KeyEvent.VK_V);
JMenu mnuHelp=new JMenu("幫助(H)");
mnuCopy=new JMenuItem("復制(C)");
mnuPaste=new JMenuItem("粘貼(P)");
JMenuItem mnuVisit=new JMenuItem("查看幫助(V)");
JMenuItem mnuAbout=new JMenuItem("關於計算器(A)");
JSeparator sep=new JSeparator();
jt1=new JTextField("0.");
jt1.setEnabled(false);
jt1.setHorizontalAlignment(JTextField.RIGHT);
mnuEdit.addMenuListener(this);
mnuCheck.addMenuListener(this);
mnuHelp.addMenuListener(this);
mnuCopy.addActionListener(this);
mnuPaste.addActionListener(this);
mnuVisit.addActionListener(this);
mnuAbout.addActionListener(this);
mnuNotepad.add(mnuEdit);
mnuNotepad.add(mnuCheck);
mnuNotepad.add(mnuHelp);
mnuEdit.add(mnuCopy);
mnuEdit.add(mnuPaste);
mnuEdit.add(sep);
mnuHelp.add(mnuVisit);
mnuHelp.add(sep);
mnuHelp.add(mnuAbout);
p1.add(mnuNotepad);
p1.add(jt1);
p2=new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.CENTER));
bM = new JButton(" ");
bM.setEnabled(false);
p2.add(bM);
Button b25=new Button("Backspace");
b25.addActionListener(this);
Button b26=new Button("CE");
b26.addActionListener(this);
Button b27=new Button("C");
b27.addActionListener(this);
p2.add(b25);
p2.add(b26);
p2.add(b27);
p3=new JPanel();
p3.setLayout(new GridLayout(4,6));
Button button1=new Button("MC");
button1.addActionListener(this);
Button button2=new Button("7");
button2.addActionListener(this);
Button button3=new Button("8");
button3.addActionListener(this);
Button button4=new Button("9");
button4.addActionListener(this);
Button button5=new Button("/");
button5.addActionListener(this);
Button button6=new Button("sqrt");
button6.addActionListener(this);
Button button7=new Button("MR");
button7.addActionListener(this);
Button button8=new Button("4");
button8.addActionListener(this);
Button button9=new Button("5");
button9.addActionListener(this);
Button button10=new Button("6");
button10.addActionListener(this);
Button button11=new Button("*");
button11.addActionListener(this);
Button button12=new Button("%");
button12.addActionListener(this);
Button button13=new Button("MS");
button13.addActionListener(this);
Button button14=new Button("1");
button14.addActionListener(this);
Button button15=new Button("2");
button15.addActionListener(this);
Button button16=new Button("3");
button16.addActionListener(this);
Button button17=new Button("-");
button17.addActionListener(this);
Button button18=new Button("1/x");
button18.addActionListener(this);
Button button19=new Button("M+");
button19.addActionListener(this);
Button button20=new Button("0");
button20.addActionListener(this);
Button button21=new Button("+/-");
button21.addActionListener(this);
Button button22=new Button(".");
button22.addActionListener(this);
Button button23=new Button("+");
button23.addActionListener(this);
Button button24=new Button("=");
button24.addActionListener(this);
p3.add(button1);p3.add(button2);
p3.add(button3);p3.add(button4);
p3.add(button5);p3.add(button6);
p3.add(button7);p3.add(button8);
p3.add(button9);p3.add(button10);
p3.add(button11);p3.add(button12);
p3.add(button13);p3.add(button14);
p3.add(button15);p3.add(button16);
p3.add(button17);p3.add(button18);
p3.add(button19);p3.add(button20);
p3.add(button21);p3.add(button22);
p3.add(button23);p3.add(button24);
setSize(250,150);
mainp=new JPanel();
mainp.setLayout(new GridLayout(3,1));
mainp.add(p1);
mainp.add(p2);
mainp.add(p3);
setContentPane(mainp);
setTitle("計算器");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String s= e.getActionCommand();
if (s.equals("復制(C)")) {
String temp = jt1.getText().trim();
Board.replace(0, Board.length(), temp);
mnuPaste.setEnabled(true);
} else if (s.equals("粘貼(p)")) {
jt1.setText(Board.toString());
} else if (s.equals("CE")) {
// 如果是CE則清除文本框
jt1.setText("0.");
} else if (s.equals("Backspace")) {
if (!jt1.getText().trim().equals("0.")) {
// 如果文本框中有內容
if (str.length() != 1 && str.length() != 0) {
jt1.setText(str.delete(str.length() - 1, str.length())
.toString());
} else {
jt1.setText("0.");
str.setLength(0);
}
}
op2 = Double.parseDouble(jt1.getText().trim());
} else if (s.equals("C")) {
// 如果是C刪除當前計算
jt1.setText("0.");
op1 = op2 = 0;
str.replace(0, str.length(), " ");
preOp = currentOp = 0;
} else if (s.equals("MC")) {
// 如果是MC則清除緩沖區
String temp = "";
memory.replace(0, memory.length(), temp);
bM.setText(" ");
} else if (s.equals("MR")) {
// 如果按鍵為MR則恢復緩沖區的數到文本框
jt1.setText(memory.toString());
} else if (s.equals("MS")) {
// 如果按鍵為MS則將文本框的數存入緩沖區
String s1 = jt1.getText().trim();
memory.replace(0, memory.length(), s1);
bM.setText("M");
} else if (s.equals("M+")) {
// 如果按鍵為MS則將文本框值與緩沖區的數相加但不顯示結果
String temp1 = jt1.getText().trim();
double dtemp = Double.parseDouble(temp1);
String temp2 = memory.toString();
dtemp += Double.parseDouble(temp2);
temp1 = String.valueOf(dtemp);
memory.replace(0, memory.length(), temp1);
} else if (s.equals("1/x")) {
// 如果按鍵為1/x則將文本框中的數據為它的倒數
String temp = jt1.getText().trim();
double dtemp = Double.parseDouble(temp);
jt1.setText("" + 1 / dtemp);
} else if (s.equals("sqrt")) {
// 如果按鍵為sqrt則將文本框中的內容求平方根
String temp = jt1.getText().trim();
double dtemp = Double.parseDouble(temp);
jt1.setText("" + Math.sqrt(dtemp));
} else if (s.equals("+")) {
str.setLength(0);
if (currentOp == 0) {
preOp = currentOp = 1;
op2 = 0;
jt1.setText("" + op1);
} else {
currentOp = preOp;
preOp = 1;
switch (currentOp) {
case 1:
op1 += op2;
jt1.setText("" + op1);
break;
case 2:
op1 -= op2;
jt1.setText("" + op1);
break;
case 3:
op1 *= op2;
jt1.setText("" + op1);
break;
case 4:
op1 /= op2;
jt1.setText("" + op1);
break;
}
}
} else if (s.equals("-")) {
str.setLength(0);
if (currentOp == 0) {
preOp = currentOp = 2;// op1=op2;op2=0;
jt1.setText("" + op1);
} else {
currentOp = preOp;
preOp = 2;
switch (currentOp) {
case 1:
op1 = op1 + op2;
jt1.setText("" + op1);
break;
case 2:
op1 = op1 - op2;
jt1.setText("" + op1);
break;
case 3:
op1 = op1 * op2;
jt1.setText("" + op1);
break;
case 4:
op1 = op1 / op2;
jt1.setText("" + op1);
break;
}
}
} else if (s.equals("*"))// *
{
str.setLength(0);
if (currentOp == 0) {
preOp = currentOp = 3;// op1=op2;op2=1;
jt1.setText("" + op1);// op1=op2;
} else {
currentOp = preOp;
preOp = 3;
switch (currentOp) {
case 1:
op1 = op1 + op2;
jt1.setText("" + op1);
break;
case 2:
op1 = op1 - op2;
jt1.setText("" + op1);
break;
case 3:
op1 = op1 * op2;
jt1.setText("" + op1);
break;
case 4:
op1 = op1 / op2;
jt1.setText("" + op1);
break;
}
}
} else if (s.equals("/"))// /
{
str.setLength(0);
if (currentOp == 0) {
preOp = currentOp = 4;// op2=1;
jt1.setText("" + op1);// op1=op2;
} else {
currentOp = preOp;
preOp = 4;
switch (currentOp) {
case 1:
op1 = op1 + op2;
jt1.setText("" + op1);
break;
case 2:
op1 = op1 - op2;
jt1.setText("" + op1);
break;
case 3:
op1 = op1 * op2;
jt1.setText("" + op1);
break;
case 4:
op1 = op1 / op2;
jt1.setText("" + op1);
break;
}
}
} else if (s.equals("="))// =
{
if (currentOp == 0) {
str.setLength(0);
jt1.setText("" + op2);
} else {
str.setLength(0);
currentOp = preOp;
switch (currentOp) {
case 1:
op1 = op1 + op2;
jt1.setText("" + op1);
break;
case 2:
op1 = op1 - op2;
jt1.setText("" + op1);
break;
case 3:
op1 = op1 * op2;
jt1.setText("" + op1);
break;
case 4:
op1 = op1 / op2;
jt1.setText("" + op1);
break;
}
currentOp = 0;
op2 = 0;
}
} else if (s.equals(".")) {
isDouble = true;
if (jt1.getText().trim().indexOf('.') != -1)
;
else {
if (jt1.getText().trim().equals("0")) {
str.setLength(0);
jt1.setText((str.append("0" + s)).toString());
}
// else
// if(jt1.getText().trim().equals("")){}//如果初時顯示為空則不做任何操作
else {
jt1.setText((str.append(s)).toString());
}
}
} else if (s.equals("0"))// 如果選擇的是"0"這個數字鍵
{
if (jt1.getText().trim().equals("0.")) {
} else {
jt1.setText(str.append(s).toString());
op2 = Double.parseDouble(jt1.getText().trim());
}
} else {
jt1.setText(str.append(s).toString());
op2 = Double.parseDouble(jt1.getText().trim());
if (currentOp == 0)
op1 = op2;
}
}
public static void main(String args[])
{
JPanelEa1 g=new JPanelEa1();
}
@Override
public void menuSelected(MenuEvent e) {
// TODO Auto-generated method stub
}
@Override
public void menuDeselected(MenuEvent e) {
// TODO Auto-generated method stub
}
@Override
public void menuCanceled(MenuEvent e) {
// TODO Auto-generated method stub
}
}
3. 用JAVA編寫一個計算器
打開IED:打開自己java編程的軟體,採用的是eclipse軟體。
建立java工程。
編寫類。
4. JAVA 編寫計算器 要代碼最簡單的
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
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 CalculatorB implements ActionListener {
private JFrame frame;
private JTextField field;
private JButton[] allButtons;
private JButton clearButton;
// 構造初始化 成員變數
public CalculatorB() {
frame = new JFrame("Calculator v1.1");
field = new JTextField(25);
allButtons = new JButton[16];
String str = "123+456-789*0.=/";
for (int i = 0; i < 16; i++) {
allButtons[i] = new JButton(str.substring(i, i + 1));
}
clearButton = new JButton("CLEAR");
// 調用界面的初始化方法
init();
// 調用設置文本框的字體和顏色 方法
setFontAndColor();
addEventHandler();
}
public void addEventHandler() {
for (int i = 0; i < allButtons.length; i++) {
allButtons[i].addActionListener(this);
clearButton.addActionListener(this);
}
}
private String op = null;
private String m = null;
private String n = null;
private boolean cls = false;
private void setResult() {
if (field.getText().equals("")) {
cls = true;
m = null;
n = null;
} else if (m != null) {
n = field.getText();
if (op.equals("+")) {
field.setText(Double.parseDouble(m) + Double.parseDouble(n)
+ "");
} else if (op.equals("-")) {
field.setText(Double.parseDouble(m) - Double.parseDouble(n)
+ "");
} else if (op.equals("*")) {
field.setText(Double.parseDouble(m) * Double.parseDouble(n)
+ "");
} else if (op.equals("/")) {
field.setText(Double.parseDouble(m) / Double.parseDouble(n)
+ "");
}
cls = true;
m = null;
n = null;
}
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();// 得到被點的按鈕名稱
if ("0123456789.".indexOf(str) != -1) {
if (cls) {
field.setText("");
cls = false;
}
field.setText(field.getText() + str);
} else if ("+-*/".indexOf(str) != -1) {
if (field.getText().equals("")) {
op = str;
} else if (m == null) {
m = field.getText();
op = str;
field.setText("");
} else if (m != null) {
setResult();
m = field.getText();
op = str;
}
} else if (str.equals("=")) {
setResult();
} else if (str.equals("CLEAR")) {
field.setText("");
m = null;
n = null;
}
}
public void init() {
frame.setLayout(new BorderLayout());
JPanel northPannel = new JPanel();
JPanel centerPannel = new JPanel();
JPanel southPannel = new JPanel();
northPannel.setLayout(new FlowLayout());
centerPannel.setLayout(new GridLayout(4, 4));
southPannel.setLayout(new FlowLayout());
northPannel.add(field);
southPannel.add(clearButton);
for (int i = 0; i < allButtons.length; i++) {
centerPannel.add(allButtons[i]);
}
frame.add(northPannel, BorderLayout.NORTH);
frame.add(southPannel, BorderLayout.SOUTH);
frame.add(centerPannel, BorderLayout.CENTER);
}
public void setFontAndColor() {
field.setFont(new Font("宋體", Font.BOLD, 20));
field.setForeground(Color.PINK);
field.setBackground(new Color(0x2a, 0x3b, 0x4f));
}
public void showMe() {
frame.pack(); // 系統調整大小---很重要
// frame.setSize(600, 400);// 自定義窗體大小
frame.setLocation(500, 400);// 設置窗體的啟動位置
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}
public static void main(String[] args) {
new CalculatorB().showMe();
}
}
以上代碼是我的原創回答,可以直接運行的代碼。並且此計算器可以實現連續計算,樓主試試去,有什麼意見和建議再提
5. 計算器java代碼
import java.awt.Color;
import java.awt.Font;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
class Normal{
double i,j;
public Normal(double num1,double num2){
i=num1;
j=num2;
}
public double puls(){
return i+j;
}
public double subtract(){
return i-j;
}
public double multiply(){
return i*j;
}
public double divide(){
return i/j;
}
public double surpuls(){
return i%j;
}
}
class scientific extends Normal{
public scientific(int num1, int num2) {
super(num1, num2);
}
}
public class calc extends JFrame{
public static void main(String[] args) {
viewNormal VN= new viewNormal("normal");
}
}
class viewNormal extends JFrame implements ActionListener{
JPanel jp1 = new JPanel(new GridLayout(4,3,5,5));
JPanel jp2 = new JPanel(new GridLayout(5,1,5,5));
JLabel jl;
JButton[] jb;
JButton jbs,jbo,jba,jbb,jbc,jby;
StringBuffer sb = new StringBuffer();
Normal normal;
int dot=0;
double fnum=0;
double lnum=0;
double result;
String sign=null;
public viewNormal(String title){
setTitle(title);
setLayout(null);
setVisible(true);
setBounds(200,200,305,350);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
jb= new JButton[12];
for(int i=0;i<9;i++){
jb[i]=new JButton(""+(i+1));
jp1.add(jb[i]);
jb[i].addActionListener(this);
}
jb[9]=new JButton(".");
jb[10]=new JButton("0");
jb[11]=new JButton("=");
jb[9].addActionListener(this);
jb[10].addActionListener(this);
jb[11].addActionListener(this);
jp1.add(jb[9]);
jp1.add(jb[10]);
jp1.add(jb[11]);
jp1.setBounds(10, 100, 200, 200);
jbs= new JButton("+");jbo= new JButton("-");jba= new JButton("*");
jbb= new JButton("/");jby= new JButton("%");jbc= new JButton("C");
jbs.addActionListener(this);jbo.addActionListener(this);jba.addActionListener(this);
jbb.addActionListener(this);jby.addActionListener(this);jbc.addActionListener(this);
//jp2.add(jby);
jp2.add(jbs);jp2.add(jbo);jp2.add(jba);jp2.add(jbb);jp2.add(jbc);
jp2.setBounds(215, 100, 70, 200);
jl= new JLabel("0",JLabel.RIGHT);
jl.setFont(new Font("Batang",Font.BOLD, 20));
jl.setBorder(new LineBorder(Color.black,2));
jl.setBackground(Color.white);
jl.setBounds(10, 40, 275, 50);
jl.setOpaque(true);
add(jl);
add(jp1);
add(jp2);
}
//+
public void sum(){
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.puls();
result=fnum;
}
//-
private void sub() {
System.out.println(sb.toString());
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.subtract();
result=fnum;
}
//*
private void mul() {
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.multiply();
result=fnum;
}
// /
private void div() {
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.divide();
result=fnum;
}
//%
private void sur() {
lnum=Double.parseDouble(sb.toString());
normal=new Normal(fnum,lnum);
fnum=normal.surpuls();
result=fnum;
}
// =
private void same(){
if(sign.equals("+")){
sum();
}
if(sign.equals("-")){
sub();
}
if(sign.equals("*")){
mul();
}
if(sign.equals("/")){
div();
}
if(sign.equals("%")){
sur();
}
}
//result
public void Result(){
if(result%1!=0)
jl.setText(""+result);
else
{
int i=(int)result;
jl.setText(""+i);
}
}
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println(sb.toString());
// 1~9
for(int i=0;i<9;i++){
if(e.getSource()==jb[i]&&!sb.toString().equals("0")){
sb.append(jb[i].getText());
jl.setText(sb.toString());
}
else if(e.getSource()==jb[i]&&sb.toString().equals("0")){
int d=sb.length();
sb.delete(0, d);
sb.append(jb[i].getText());
jl.setText(sb.toString());
}
}
// 0
if(e.getSource()==jb[10]&&!sb.toString().equals("0")){
sb.append(jb[10].getText());
jl.setText(sb.toString());
}
// .
if(e.getSource()==jb[9]&&dot==0&&!sb.toString().equals("")){
dot++;
sb.append(jb[9].getText());
jl.setText(sb.toString());
}
// =
if(e.getSource()==jb[11]&&!sb.toString().equals("")){
same();
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
// +
if(e.getSource()==jbs&&!sb.toString().equals("")){
if(sign!="+"&&sign!=null)
same();
else
sum();
sign ="+";
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
//-
if(e.getSource()==jbo&&!sb.toString().equals("")){
if(fnum==0)
fnum=2*Double.parseDouble(sb.toString());
if(sign!="-"&&sign!=null)
same();
else
sub();
sign ="-";
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
//*
if(e.getSource()==jba&&!sb.toString().equals("")){
if(fnum==0)
fnum=1;
if(sign!="*"&&sign!=null)
same();
else
mul();
sign ="*";
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
// /
if(e.getSource()==jbb&&!sb.toString().equals("")){
if(fnum==0)
fnum=Math.pow(Double.parseDouble(sb.toString()),2);
if(sign!="/"&&sign!=null)
same();
else
div();
sign ="/";
Result();
int d=sb.length();
sb.delete(0, d);
dot=0;
}
//%
// if(e.getSource()==jby&&!sb.toString().equals("")){
// if(fnum==0){
// fnum=Double.parseDouble(sb.toString());
// result=fnum;
// }
// else {
// if(sign!="%"&&sign!=null)
// same();
// else{
// lnum=Double.parseDouble(sb.toString());
// normal=new Normal(fnum,lnum);
// fnum=normal.surpuls();
// result=fnum;
// }
// }
// sign ="%";
// Result();
// int d=sb.length();
// sb.delete(0, d);
// dot=0;
// }
//clear
if(e.getSource()==jbc){
int d=sb.length();
sb.delete(0, d);
jl.setText("0");
dot=0;
fnum=0;
lnum=0;
sign=null;
}
}
}
class viewScientific extends viewNormal{
public viewScientific(String title){
super(title);
setBounds(200,200,800,500);
}
}
//等號以後輸入符號用不了, String轉 double 本來就有錯誤,你可以用我的擴展成科學型的。
6. java編一個計算器的代碼
用Applet還是用Application?
我以前老師好像也布置過一個計算器是Applet的
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
//import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class calculator extends Applet implements ActionListener {
/**
*
*/
//private static final long serialVersionUID = 3114597813287650283L;
/* (non-Javadoc)
* @see java.applet.Applet#init()
*/
public int operator = 1; //運算符判斷:1-加,2-減,3-乘,4-除;
public double accumulator=0; //運算的累加器;
public double digit = 0;
public boolean bool = true;
public boolean boolca = false;
public String text="0.0";
/*窗體控制項*/
public JTextField tf_AccepteData = new JTextField();
public Button bt_Digit;
public Button bt_dot = new Button(".");
public Button bt_add = new Button("+");
public Button bt_plus = new Button("-");
public Button bt_mul = new Button("*");
public Button bt_div = new Button("/");
public Button bt_equal = new Button("=");
public Button bt_clear = new Button("C");
public Button bt_inverse = new Button("1/x");
public Button bt_non = new Button("+/-");
public Button bt_sqrt = new Button("sqrt");
public double scan()
{
text = tf_AccepteData.getText();
try{
digit = Double.parseDouble(text);
}catch(Exception msg){
msg.printStackTrace();
}
return digit;
}
public void accumulate()
{
if(!tf_AccepteData.getText().equals("")){
switch(operator){
case 1:
accumulator += digit;
tf_AccepteData.setText("" + accumulator);
break;
case 2:
accumulator -= digit;
tf_AccepteData.setText("" + accumulator);
break;
case 3:
accumulator *= digit;
tf_AccepteData.setText("" + accumulator);
break;
case 4:
if(digit == 0){
tf_AccepteData.setText("除數不能為零");
operator = 1;
accumulator = 0;
bool = true;
digit = 0;
text="";
}else{
accumulator /=digit;
tf_AccepteData.setText("" + accumulator);
}
break;
default:
break;
}
operator = 1;
}
}
public void init() {
/*初始化窗體*/
setLayout(null);
setSize(225,200);
setBackground(Color.orange);
add(tf_AccepteData);
tf_AccepteData.setHorizontalAlignment(SwingConstants.RIGHT);
tf_AccepteData.setSize(200, 25);
tf_AccepteData.setLocation(10, 10);
tf_AccepteData.setEnabled(false);
tf_AccepteData.setText("0.0");
text = tf_AccepteData.getText();
for(int i= 0; i<=9; i++){
bt_Digit = new Button("" + i);
add(bt_Digit);
bt_Digit.setSize(30, 30);
if(i>=7&&i<=9)
bt_Digit.setLocation((15+40*(i-7)), 50);
if(i>=4&&i<=6)
bt_Digit.setLocation((15+40*(i-4)), 85);
if(i>=1&&i<=3)
bt_Digit.setLocation((15+40*(i-1)), 120);
if(i==0)
bt_Digit.setLocation(15, 155);
bt_Digit.addActionListener(this);
}
/*
* 小數點
*/
add(bt_dot);
bt_dot.setSize(30, 30);
bt_dot.setLocation(95, 155);
bt_dot.addActionListener(this/*new ActionListener()*/);/*{
public void actionPerformed(ActionEvent e) {
}
});*/
/*
* 加法運算
*/
add(bt_add);
bt_add.setSize(30, 30);
bt_add.setLocation(135, 155);
bt_add.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
accumulate();
operator = 1;
bool =true;
boolca = true;
digit = 0;
}
});
/*
* 減法運算
*/
add(bt_plus);
bt_plus.setSize(30, 30);
bt_plus.setLocation(135, 120);
bt_plus.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
accumulate();
operator = 2;
bool =true;
boolca = true;
digit = 0;
}
});
/*
* 乘法運算
*/
add(bt_mul);
bt_mul.setSize(30, 30);
bt_mul.setLocation(135, 85);
bt_mul.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
accumulate();
operator = 3;
bool =true;
boolca = true;
digit = 1;
}
});
/*
* 除法運算
*/
add(bt_div);
bt_div.setSize(30, 30);
bt_div.setLocation(135, 50);
bt_div.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
accumulate();
operator = 4;
bool =true;
boolca = true;
digit = 1;
}
});
/*
* 倒數
*/
add(bt_inverse);
bt_inverse.setSize(30, 30);
bt_inverse.setLocation(175, 120);
bt_inverse.addActionListener(new ActionListener(){
double data=0;
public void actionPerformed(ActionEvent e) {
data = scan();
if(digit==0){
tf_AccepteData.setText("取倒分母不能為零!");
operator = 1;
accumulator = 0;
bool = true;
digit = 0;
text="";
}else{
tf_AccepteData.setText("" + 1.0/data);
}
if(!boolca)
operator = 1;
}
});
/*
* 數學平方根
*/
add(bt_sqrt);
bt_sqrt.setSize(30, 30);
bt_sqrt.setLocation(175, 85);
bt_sqrt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
scan();
if(digit<0){
tf_AccepteData.setText("函數輸入無效!");
operator = 1;
accumulator = 0;
bool = true;
digit = 0;
text="";
}else{
digit = Math.sqrt(digit);
tf_AccepteData.setText("" + digit);
}
if(!boolca)
operator = 1;
}
});
/*
* 取反
*/
add(bt_non);
bt_non.setSize(30, 30);
bt_non.setLocation(55, 155);
bt_non.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
try{
digit = -Double.parseDouble(tf_AccepteData.getText());
tf_AccepteData.setText("" + digit);
}catch(Exception msg){
msg.printStackTrace();
}
if(!boolca)
operator = 1;
}
});
/*
* 等於
*/
add(bt_equal);
bt_equal.setSize(30, 30);
bt_equal.setLocation(175, 155);
bt_equal.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
accumulate();
operator = 1;
bool =true;
digit = 0;
}
});
/*
* 清零運算
*/
add(bt_clear);
bt_clear.setSize(30, 30);
bt_clear.setLocation(175, 50);
bt_clear.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
operator = 1;
accumulator = 0;
bool = true;
digit = 0;
text="";
tf_AccepteData.setText("0.0");
}
});
}
public void actionPerformed(ActionEvent e){
if(bool){
tf_AccepteData.setText("");
bool = false;
}
text = tf_AccepteData.getText();
if((text+e.getActionCommand()).indexOf(".")!=(text+e.getActionCommand()).lastIndexOf(".")) return;
text += e.getActionCommand();
if(text.equals("."))
text = "0"+text;
tf_AccepteData.setText(text);
scan();
}
}
還要寫一個CalculatorTest.html網頁文件代碼如下,寫好雙擊運行CalculatorTest.html就可以了
<!-------------------------CalculatorTest.html ------------------------>
<HTML>
<HEAD>
<TITLE>
小應用程序——一個簡單的計算器模型
</TITLE>
</HEAD>
<BODY bgcolor = blue text = yellow >
<center>
<marquee behavior=alternate width = 300 height = 40><br>實現加、減、乘、除四種基本運算</marquee>
<br><br><br>
<APPLET ALIGN = middle CODE = "calculator.class" WIDTH = 225 HEIGHT = 200></APPLET>
<br><br><br>
<input type = button value = " 退出 " onClick="javascript:window.close()">
</center>
<BR>
</BODY>
</HTML>
7. 用java實現一個簡單的計算器。
說實在的,你寫的這個計算器不怎麼樣。特別是布局。
我給你一個很簡單的吧。你自己學習一下。。
import java.awt.*;
import java.awt.event.*;
/**
*
* @author zzj
*
*/
public class Jisuanqi extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
TextField txt;
private Button[] b = new Button[17];
private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "清空", "0", "=", "/", "關閉" };
static double a;
static String s, str;//定義變數 創建對像
public static void main(String args[]) {
(new Jisuanqi()).frame();
}
public void frame() {
Frame fm = new Frame("簡單計算器");
for (int i = 0; i <= 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i <= 15; i++) {
p2.add(b[i]);
} //創建按鈕 並添加到P2
b[16].setBackground(Color.yellow);
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i <= 16; i++) {
b[i].addActionListener(new buttonlistener());//添加監聽器
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "North");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);//都是些窗中設置 添加相關組件和監聽器
}
public void windowClosing(WindowEvent e) {
System.exit(0);//退出系統
}
class buttonlistener implements ActionListener {//編寫監聽器事件 通過按鍵得出給果
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
jisuan();
str = String.valueOf(a);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";
} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());
if (btn.getLabel() == "清空")
txt.setText("");
}
}
public void jisuan() {//編寫具體計算方法
if (s == "+")
a += Double.parseDouble(txt.getText());
else if (s == "-")
a -= Double.parseDouble(txt.getText());
else if (s == "*")
a *= Double.parseDouble(txt.getText());
else if (s == "/")
a /= Double.parseDouble(txt.getText());
else
a = Double.parseDouble(txt.getText());
}
}
}
class close implements ActionListener {//退出
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}