❶ 編寫java程序簡單計算器
主要涉及的知識點: 類的寫法, 以及方法的調用 .建議多做練習. 如果有看不懂的地方. 可以繼續追問,一起討論.
參考代碼如下
//Number類
classNumber{
privateintn1;//私有的整型數據成員n1
privateintn2;//私有的整型數據成員n2
//通過構造函數給n1和n2賦值
publicNumber(intn1,intn2){
this.n1=n1;
this.n2=n2;
}
//加法
publicintaddition(){
returnn1+n2;
}
//減法
publicintsubtration(){
returnn1-n2;
}
//乘法
publicintmultiplication(){
returnn1*n2;
}
//除法(可能除不盡,所以使用double作為返回類型)
publicdoubledivision(){
returnn1*1.0/n2;//通過n1*1.0把計算結果轉換成double類型.
}
}
//Exam4類
publicclassExam4{
publicstaticvoidmain(String[]args){
Numbernumber=newNumber(15,6);//創建Number類的對象
//下面的是調用方法得到返回值進行輸出顯示
System.out.println("加法"+number.addition());
System.out.println("減法"+number.subtration());
System.out.println("乘法"+number.multiplication());
System.out.println("除法"+number.division());
}
}
❷ 用java語言編寫一個計算器的程序
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("*****************簡易計算器****************");
System.out.println("*\t\t\t\t\t*");
System.out.println("* 使用說明: 1.加法 2.減法 3.乘法 4.除法 *");
System.out.println("*\t\t\t\t\t*");
System.out.println("*****************************************");
for(int i=0;i<100;i++){
System.out.print("\n請選擇運算規則:");
int num = input.nextInt();
switch(num){
case 1:
System.out.println("\n******你選擇了加法******\n");
System.out.print("請輸入第1個加數:");
int jiashu1 = input.nextInt();
System.out.print("請輸入第2個加數:");
int jiashu2 = input.nextInt();
System.out.println("運算結果為:" + jiashu1 + " + " + jiashu1 + " = " + (jiashu1 + jiashu2));
break;
case 2:
System.out.println("\n******你選擇了減法******\n");
System.out.print("請輸入被減數:");
int jianshu1 = input.nextInt();
System.out.print("請輸入減數:");
int jianshu2 = input.nextInt();
System.out.println("運算結果為:" + jianshu1 + " - " + jianshu2 + " = " + (jianshu1 - jianshu2));
break;
case 3:
System.out.println("\n******你選擇了乘法******\n");
System.out.print("請輸入第1個因數:");
int chengfa1 = input.nextInt();
System.out.print("請輸入第2個因數:");
int chengfa2 = input.nextInt();
System.out.println("運算結果為:" + chengfa1 + " * " + chengfa2 + " = " + (chengfa1 * chengfa2));
break;
case 4:
System.out.println("\n******你選擇了除法******\n");
System.out.print("請輸入被除數:");
double chufa1 = input.nextInt();
System.out.print("請輸入除數:");
double chufa2 = input.nextInt();
System.out.println("運算結果為:" + chufa1 + " / " + chufa2 + " = " + (chufa1 / chufa2) + " 余 " + (chufa1 % chufa2));
break;
default:
System.out.println("\n你的選擇有錯,請重新選擇!");
break;
}
}
}
}
❸ 用Java編寫一個簡單的計算器程序
import java.awt.*;
import java.awt.event.*;
public class CalcAppDemo extends Frame{
private TextField t_result;
private Panel p_main; //主面板
private Panel p_num; //數字面板
private Panel p_oper; //操作符面板
private Panel p_show; //顯示面板
private Button b_num[]; //數字按鈕
private Button b_oper[]; //操作符面板
public CalcAppDemo(String title){
setTitle(title);
t_result = new TextField("0.0", 21);
p_main = new Panel();
p_num = new Panel();
p_oper = new Panel();
p_show = new Panel();
p_main.setLayout(new BorderLayout());
p_num.setLayout(new GridLayout(4, 3, 1, 1));
p_oper.setLayout(new GridLayout(4, 2, 1, 1));
b_num = new Button[12];
for(int i=0; i<9; i++)
{
b_num[i] = new Button(new Integer(i+1).toString());
}
b_num[9] = new Button("0");
b_num[10] = new Button("cls");
b_num[11] = new Button(".");
for(int i=0; i<12; i++)
{
p_num.add(b_num[i]);
}
b_oper = new Button[8];
b_oper[0] = new Button("+");
b_oper[1] = new Button("-");
b_oper[2] = new Button("*");
b_oper[3] = new Button("/");
b_oper[4] = new Button("pow");
b_oper[5] = new Button("sqrt");
b_oper[6] = new Button("+/-");
b_oper[7] = new Button("=");
for(int i=0; i<8; i++) //
{
p_oper.add(b_oper[i]);
}
t_result.setEditable(false);
p_show.add(t_result, BorderLayout.NORTH);
p_main.add(p_show, BorderLayout.NORTH);
p_main.add(p_num, BorderLayout.WEST);
p_main.add(p_oper, BorderLayout.EAST);
this.add(p_main, BorderLayout.CENTER);
setSize(400, 400);
setResizable(false);
pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
ButtonListener b1 = new ButtonListener();
for(int i=0; i<12; i++)
{
b_num[i].addActionListener(b1);
}
for(int i=0; i<8; i++)
{
b_oper[i].addActionListener(b1);
}
}
class ButtonListener implements ActionListener
{
private String lastOp; //存儲上一此操作符
private String strVal; //存儲數字對應的字元串
private double total; //總數
private double number; //存儲新輸入的數
private boolean firsttime; //判斷是否第一次按下的是操作符按鈕
private boolean operatorPressed;//判斷是否已經按過操作符按鈕
ButtonListener()
{
firsttime = true;
strVal = "";
}
//事件處理器
public void actionPerformed(ActionEvent e)
{
String s = ((Button)e.getSource()).getLabel().trim();
if(Character.isDigit(s.charAt(0)))
{//判斷是操作數還是操作符
handleNumber(s);
}
else
{
calculate(s);
}
}
//判斷是一元操作符還是二元操作符,並根據操作符類型做計算
void calculate(String op)
{
operatorPressed = true;
if(firsttime&&! isUnary(op))
{
total = getNumberOnDisplay();
firsttime = false;
}
if(isUnary(op))
{
handleUnaryOp(op);
}
else if(lastOp != null)
{
handleBinaryOp(lastOp);
}
if(! isUnary(op))
{
lastOp = op;
}
}
//判斷是否一元操作符
boolean isUnary(String s)
{
return s.equals("=")
||s.equals("cls")||s.equals("sqrt")
||s.equals("+/-")||s.equals(".");
}
//處理一元操作符
void handleUnaryOp(String op)
{
if(op.equals("+/-"))
{//
number = negate(getNumberOnDisplay() + "");
t_result.setText("");
t_result.setText(number + "");
return;
}else if(op.equals("."))
{
handleDecPoint();
return;
}else if(op.equals("sqrt"))
{
number = Math.sqrt(getNumberOnDisplay());
t_result.setText("");
t_result.setText(number + "");
return;
}else if(op.equals("="))
{//
if(lastOp!= null && !isUnary(lastOp))
{
handleBinaryOp(lastOp);
}
lastOp = null;
firsttime = true;
return;
}else
{
clear();
}
}
//處理二元運算符
void handleBinaryOp(String op)
{
if(op.equals("+"))
{
total +=number;
}else if(op.equals("-"))
{
total -=number;
}else if(op.equals("*"))
{
total *=number;
}else if(op.equals("/"))
{
try
{
total /=number;
}catch(ArithmeticException ae){}
}else if(op.equals("pow"))
total = Math.pow(total, number);
//t_result.setText("");
lastOp = null;
// strVal = "";
number = 0;
t_result.setText(total + "");
}
//該方法用於處理數字按鈕
void handleNumber(String s)
{
if(!operatorPressed)
{
strVal += s;
}else
{
operatorPressed = false;
strVal = s;
}
//
number = new Double(strVal).doubleValue();
t_result.setText("");
t_result.setText(strVal);
}
//該方法用於按下"."按鈕
void handleDecPoint()
{
operatorPressed = false;
//
if(strVal.indexOf(".")<0)
{
strVal += ".";
}
t_result.setText("");
t_result.setText(strVal);
}
//該方法用於將一個數求反
double negate(String s)
{
operatorPressed = false;
//如果是一個整數,去掉小數點後面的0
if(number == (int)number)
{
s = s.substring(0,s.indexOf("."));
}
//如果無"-"增加在該數的前面
if(s.indexOf("-")<0)
{
strVal = "-" + s;
}
else
{
strVal = s.substring(1);
}
return new Double(strVal).doubleValue();
}
//將顯示框中的值轉換成Double
double getNumberOnDisplay()
{
return new Double(t_result.getText()).doubleValue();
}
//清除屏幕並設置所有的標識
void clear()
{
firsttime = true;
lastOp = null;
strVal = "";
total = 0;
number = 0;
t_result.setText("0");
}
}
public static void main(String[] args) {
CalcAppDemo c = new CalcAppDemo("簡單的計算器程序");
c.setVisible(true);
}
}
❹ 求java編寫的租金計算器小程序
importjava.awt.Container;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.FocusAdapter;
importjava.awt.event.FocusEvent;
importjava.sql.Date;
importjava.util.Calendar;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JTextField;
publicclassZuJinextendsJFrame{
/**
*(結束日期-開始日期)÷30×月租金+業務費用+其他費用=總費用
〔(結束日期-開始日期)÷30×月租金+業務費用+其他費用〕÷合租人員=平均費用
需要彈出一個租金計算器對話框分為租金計算信息與租金計算結果兩部分
*/
publicZuJin(){
Containerc=getContentPane();
c.setLayout(newGridLayout(5,4));
JLabelj1=newJLabel("開始日期");
c.add(j1);
JTextFieldjt1=newJTextField(10);
c.add(jt1);
JLabelj2=newJLabel("結束日期");
c.add(j2);
JTextFieldjt2=newJTextField("");
c.add(jt2);
JLabelj3=newJLabel("月租金(元)");
c.add(j3);
JTextFieldjt3=newJTextField(5);
c.add(jt3);
JLabelj4=newJLabel("業務費(元)");
c.add(j4);
JTextFieldjt4=newJTextField(5);
c.add(jt4);
JLabelj5=newJLabel("其他費用(元)");
c.add(j5);
JTextFieldjt5=newJTextField(5);
c.add(jt5);
JLabelj6=newJLabel("合租人員數量");
c.add(j6);
JTextFieldjt6=newJTextField(3);
c.add(jt6);
JLabelj7=newJLabel("總費用(元)");
c.add(j7);
JTextFieldjt7=newJTextField(5);
jt7.setEditable(false);
c.add(jt7);
JLabelj8=newJLabel("平均費用(元)");
c.add(j8);
JTextFieldjt8=newJTextField(5);
jt8.setEditable(false);
c.add(jt8);
JButtonjb1=newJButton("計算");
c.add(jb1);
jt1.addFocusListener(newFocusAdapter()
{
@Override
publicvoidfocusGained(FocusEvente)
{
if(jt1.getText().equals("格式為:0000-00-00")){
jt1.setText("");
}
}
@Override
publicvoidfocusLost(FocusEvente)
{
if(jt1.getText().equals("")){
jt1.setText("格式為:0000-00-00");
}
}
});
jt2.addFocusListener(newFocusAdapter()
{
@Override
publicvoidfocusGained(FocusEvente)
{
if(jt2.getText().equals("格式為:0000-00-00")){
jt2.setText("");
}
}
@Override
publicvoidfocusLost(FocusEvente)
{
if(jt2.getText().equals("")){
jt2.setText("格式為:0000-00-00");
}
}
});
jb1.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEventarg0){
//TODOAuto-generatedmethodstub
Dated1=Date.valueOf(jt1.getText());//開始日期
Dated2=Date.valueOf(jt2.getText());//結束日期
Calendarc1=Calendar.getInstance();
c1.setTime(d1);
Calendarc2=Calendar.getInstance();
c2.setTime(d2);
intday1=c1.get(Calendar.DAY_OF_YEAR);
intday2=c2.get(Calendar.DAY_OF_YEAR);
intdays=day2-day1;
doublemoney1=Double.valueOf(jt3.getText());//月租金
doublemoney2=Double.valueOf(jt4.getText());//業務費
doublemoney3=Double.valueOf(jt5.getText());//其他費用
intman=Integer.valueOf(jt6.getText());//人數
doublemoney4=days/30*money1+money2+money3;
doublemoney5=0.0;
if(man!=0){
money5=money4/man;
}
else{
money5=money4;
}
jt7.setText(String.valueOf(money4));
jt8.setText(String.valueOf(money5));
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(400,400,500,300);
setVisible(true);
setTitle("租金計算器");
}
publicstaticvoidmain(String[]args){
ZuJinzj=newZuJin();
}
}
丑是丑了點 用還是可以用的。
❺ 請問誰能用java語言,為我寫一個計算器的小程序
<!--開始 -->
<STYLE>BODY {
BACKGROUND-ATTACHMENT: fixed; BACKGROUND-COLOR: #edf0e1; COLOR: #0001fc; FONT-FAMILY: "宋體", "Arial", "Times New Roman"; FONT-SIZE: 9pt
}
TD {
FONT-FAMILY: "宋體", "Arial Narrow", "Times New Roman"; FONT-SIZE: 9pt; font-color: #000000
}
</STYLE>
<SCRIPT language=javascript>
<!--
var endNumber=true
var mem=0
var carry=10
var hexnum="0123456789abcdef"
var angle="d"
var stack=""
var level="0"
var layer=0
//數字鍵
function inputkey(key)
{
var index=key.charCodeAt(0);
if ((carry==2 && (index==48 || index==49))
|| (carry==8 && index>=48 && index<=55)
|| (carry==10 && (index>=48 && index<=57 || index==46))
|| (carry==16 && ((index>=48 && index<=57) || (index>=97 && index<=102))))
if(endNumber)
{
endNumber=false
document.calc.display.value = key
}
else if(document.calc.display.value == null || document.calc.display.value == "0")
document.calc.display.value = key
else
document.calc.display.value += key
}
function changeSign()
{
if (document.calc.display.value!="0")
if(document.calc.display.value.substr(0,1) == "-")
document.calc.display.value = document.calc.display.value.substr(1)
else
document.calc.display.value = "-" + document.calc.display.value
}
//函數鍵
function inputfunction(fun,shiftfun)
{
endNumber=true
if (document.calc.shiftf.checked)
document.calc.display.value=decto(funcalc(shiftfun,(todec(document.calc.display.value,carry))),carry)
else
document.calc.display.value=decto(funcalc(fun,(todec(document.calc.display.value,carry))),carry)
document.calc.shiftf.checked=false
document.calc.hypf.checked=false
inputshift()
}
function inputtrig(trig,arctrig,hyp,archyp)
{
if (document.calc.hypf.checked)
inputfunction(hyp,archyp)
else
inputfunction(trig,arctrig)
}
//運算符
function operation(join,newlevel)
{
endNumber=true
var temp=stack.substr(stack.lastIndexOf("(")+1)+document.calc.display.value
while (newlevel!=0 && (newlevel<=(level.charAt(level.length-1))))
{
temp=parse(temp)
level=level.slice(0,-1)
}
if (temp.match(/^(.*\d[\+\-\*\/\%\^\&\|x])?([+-]?[0-9a-f\.]+)$/))
document.calc.display.value=RegExp.$2
stack=stack.substr(0,stack.lastIndexOf("(")+1)+temp+join
document.calc.operator.value=" "+join+" "
level=level+newlevel
}
//括弧
function addbracket()
{
endNumber=true
document.calc.display.value=0
stack=stack+"("
document.calc.operator.value=" "
level=level+0
layer+=1
document.calc.bracket.value="(="+layer
}
function disbracket()
{
endNumber=true
var temp=stack.substr(stack.lastIndexOf("(")+1)+document.calc.display.value
while ((level.charAt(level.length-1))>0)
{
temp=parse(temp)
level=level.slice(0,-1)
}
document.calc.display.value=temp
stack=stack.substr(0,stack.lastIndexOf("("))
document.calc.operator.value=" "
level=level.slice(0,-1)
layer-=1
if (layer>0)
document.calc.bracket.value="(="+layer
else
document.calc.bracket.value=""
}
//等號
function result()
{
endNumber=true
while (layer>0)
disbracket()
var temp=stack+document.calc.display.value
while ((level.charAt(level.length-1))>0)
{
temp=parse(temp)
level=level.slice(0,-1)
}
document.calc.display.value=temp
document.calc.bracket.value=""
document.calc.operator.value=""
stack=""
level="0"
}
//修改鍵
function backspace()
{
if (!endNumber)
{
if(document.calc.display.value.length>1)
document.calc.display.value=document.calc.display.value.substring(0,document.calc.display.value.length - 1)
else
document.calc.display.value=0
}
}
function clearall()
{
document.calc.display.value=0
endNumber=true
stack=""
level="0"
layer=""
document.calc.operator.value=""
document.calc.bracket.value=""
}
//轉換鍵
function inputChangCarry(newcarry)
{
endNumber=true
document.calc.display.value=(decto(todec(document.calc.display.value,carry),newcarry))
carry=newcarry
document.calc.sin.disabled=(carry!=10)
document.calc.cos.disabled=(carry!=10)
document.calc.tan.disabled=(carry!=10)
document.calc.bt.disabled=(carry!=10)
document.calc.pi.disabled=(carry!=10)
document.calc.e.disabled=(carry!=10)
document.calc.kp.disabled=(carry!=10)
document.calc.k2.disabled=(carry<=2)
document.calc.k3.disabled=(carry<=2)
document.calc.k4.disabled=(carry<=2)
document.calc.k5.disabled=(carry<=2)
document.calc.k6.disabled=(carry<=2)
document.calc.k7.disabled=(carry<=2)
document.calc.k8.disabled=(carry<=8)
document.calc.k9.disabled=(carry<=8)
document.calc.ka.disabled=(carry<=10)
document.calc.kb.disabled=(carry<=10)
document.calc.kc.disabled=(carry<=10)
document.calc.kd.disabled=(carry<=10)
document.calc.ke.disabled=(carry<=10)
document.calc.kf.disabled=(carry<=10)
}
function inputChangAngle(angletype)
{
endNumber=true
angle=angletype
if (angle=="d")
document.calc.display.value=radiansToDegress(document.calc.display.value)
else
document.calc.display.value=degressToRadians(document.calc.display.value)
endNumber=true
}
function inputshift()
{
if (document.calc.shiftf.checked)
{
document.calc.bt.value="deg "
document.calc.ln.value="exp "
document.calc.log.value="expd"
if (document.calc.hypf.checked)
{
document.calc.sin.value="ahs "
document.calc.cos.value="ahc "
document.calc.tan.value="aht "
}
else
{
document.calc.sin.value="asin"
document.calc.cos.value="acos"
document.calc.tan.value="atan"
}
document.calc.sqr.value="x^.5"
document.calc.cube.value="x^.3"
document.calc.floor.value="小數"
}
else
{
document.calc.bt.value="d.ms"
document.calc.ln.value=" ln "
document.calc.log.value="log "
if (document.calc.hypf.checked)
{
document.calc.sin.value="hsin"
document.calc.cos.value="hcos"
document.calc.tan.value="htan"
}
else
{
document.calc.sin.value="sin "
document.calc.cos.value="cos "
document.calc.tan.value="tan "
}
document.calc.sqr.value="x^2 "
document.calc.cube.value="x^3 "
document.calc.floor.value="取整"
}
}
//存儲器部分
function clearmemory()
{
mem=0
document.calc.memory.value=" "
}
function getmemory()
{
endNumber=true
document.calc.display.value=decto(mem,carry)
}
function putmemory()
{
endNumber=true
if (document.calc.display.value!=0)
{
mem=todec(document.calc.display.value,carry)
document.calc.memory.value=" M "
}
else
document.calc.memory.value=" "
}
function addmemory()
{
endNumber=true
mem=parseFloat(mem)+parseFloat(todec(document.calc.display.value,carry))
if (mem==0)
document.calc.memory.value=" "
else
document.calc.memory.value=" M "
}
function multimemory()
{
endNumber=true
mem=parseFloat(mem)*parseFloat(todec(document.calc.display.value,carry))
if (mem==0)
document.calc.memory.value=" "
else
document.calc.memory.value=" M "
}
//十進制轉換
function todec(num,oldcarry)
{
if (oldcarry==10 || num==0) return(num)
var neg=(num.charAt(0)=="-")
if (neg) num=num.substr(1)
var newnum=0
for (var index=1;index<=num.length;index++)
newnum=newnum*oldcarry+hexnum.indexOf(num.charAt(index-1))
if (neg)
newnum=-newnum
return(newnum)
}
function decto(num,newcarry)
{
var neg=(num<0)
if (newcarry==10 || num==0) return(num)
num=""+Math.abs(num)
var newnum=""
while (num!=0)
{
newnum=hexnum.charAt(num%newcarry)+newnum
num=Math.floor(num/newcarry)
}
if (neg)
newnum="-"+newnum
return(newnum)
}
//表達式解析
function parse(string)
{
if (string.match(/^(.*\d[\+\-\*\/\%\^\&\|x\<])?([+-]?[0-9a-f\.]+)([\+\-\*\/\%\^\&\|x\<])([+-]?[0-9a-f\.]+)$/))
return(RegExp.$1+cypher(RegExp.$2,RegExp.$3,RegExp.$4))
else
return(string)
}
//數學運算和位運算
function cypher(left,join,right)
{
left=todec(left,carry)
right=todec(right,carry)
if (join=="+")
return(decto(parseFloat(left)+parseFloat(right),carry))
if (join=="-")
return(decto(left-right,carry))
if (join=="*")
return(decto(left*right,carry))
if (join=="/" && right!=0)
return(decto(left/right,carry))
if (join=="%")
return(decto(left%right,carry))
if (join=="&")
return(decto(left&right,carry))
if (join=="|")
return(decto(left|right,carry))
if (join=="^")
return(decto(Math.pow(left,right),carry))
if (join=="x")
return(decto(left^right,carry))
if (join=="<")
return(decto(left<<right,carry))
alert("除數不能為零")
return(left)
}
//函數計算
function funcalc(fun,num)
{
with(Math)
{
if (fun=="pi")
return(PI)
if (fun=="e")
return(E)
if (fun=="abs")
return(abs(num))
if (fun=="ceil")
return(ceil(num))
if (fun=="round")
return(round(num))
if (fun=="floor")
return(floor(num))
if (fun=="deci")
return(num-floor(num))
if (fun=="ln" && num>0)
return(log(num))
if (fun=="exp")
return(exp(num))
if (fun=="log" && num>0)
return(log(num)*LOG10E)
if (fun=="expdec")
return(pow(10,num))
if (fun=="cube")
return(num*num*num)
if (fun=="cubt")
return(pow(num,1/3))
if (fun=="sqr")
return(num*num)
if (fun=="sqrt" && num>=0)
return(sqrt(num))
if (fun=="!")
return(factorial(num))
if (fun=="recip" && num!=0)
return(1/num)
if (fun=="dms")
return(dms(num))
if (fun=="deg")
return(deg(num))
if (fun=="~")
return(~num)
if (angle=="d")
{
if (fun=="sin")
return(sin(degressToRadians(num)))
if (fun=="cos")
return(cos(degressToRadians(num)))
if (fun=="tan")
return(tan(degressToRadians(num)))
if (fun=="arcsin" && abs(num)<=1)
return(radiansToDegress(asin(num)))
if (fun=="arccos" && abs(num)<=1)
return(radiansToDegress(acos(num)))
if (fun=="arctan")
return(radiansToDegress(atan(num)))
}
else
{
if (fun=="sin")
return(sin(num))
if (fun=="cos")
return(cos(num))
if (fun=="tan")
return(tan(num))
if (fun=="arcsin" && abs(num)<=1)
return(asin(num))
if (fun=="arccos" && abs(num)<=1)
return(acos(num))
if (fun=="arctan")
return(atan(num))
}
if (fun=="hypsin")
return((exp(num)-exp(0-num))*0.5)
if (fun=="hypcos")
return((exp(num)+exp(-num))*0.5)
if (fun=="hyptan")
return((exp(num)-exp(-num))/(exp(num)+exp(-num)))
if (fun=="ahypsin" | fun=="hypcos" | fun=="hyptan")
{
alert("對不起,公式還沒有查到!")
return(num)
}
alert("超出函數定義范圍")
return(num)
}
}
function factorial(n)
{
n=Math.abs(parseInt(n))
var fac=1
for (;n>0;n-=1)
fac*=n
return(fac)
}
function dms(n)
{
var neg=(n<0)
with(Math)
{
n=abs(n)
var d=floor(n)
var m=floor(60*(n-d))
var s=(n-d)*60-m
}
var dms=d+m/100+s*0.006
if (neg)
dms=-dms
return(dms)
}
function deg(n)
{
var neg=(n<0)
with(Math)
{
n=abs(n)
var d=floor(n)
var m=floor((n-d)*100)
var s=(n-d)*100-m
}
var deg=d+m/60+s/36
if (neg)
deg=-deg
return(deg)
}
function degressToRadians(degress)
{
return(degress*Math.PI/180)
}
function radiansToDegress(radians)
{
return(radians*180/Math.PI)
}
//界面
//-->
</SCRIPT>
<!--written by GoldHuman li hai--><!--2000.8-->
<META content="Microsoft FrontPage 4.0" name=GENERATOR></HEAD>
<BODY>
<DIV align=center>
<FORM name=calc>
<TABLE height=250 width=500 border=1>
<TBODY>
<TR>
<TD height=50>
<TABLE width=500>
<TBODY>
<TR>
<TD></TD>
<TD>
<DIV align=center><INPUT readOnly size=40 value=0 name=display> </DIV></TD></TR></TBODY></TABLE></TD></TR>
<TR>
<TD>
<TABLE width=500>
<TBODY>
<TR>
<TD width=290><INPUT onclick=inputChangCarry(16) type=radio name=carry> 十六進制 <INPUT onclick=inputChangCarry(10) type=radio CHECKED name=carry> 十進制 <INPUT onclick=inputChangCarry(8) type=radio name=carry> 八進制 <INPUT onclick=inputChangCarry(2) type=radio name=carry> 二進制 </TD>
<TD></TD>
<TD width=135><INPUT onclick="inputChangAngle('d')" type=radio CHECKED value=d name=angle> 角度制 <INPUT onclick="inputChangAngle('r')" type=radio value=r name=angle> 弧度制 </TD></TR></TBODY></TABLE>
<TABLE width=500>
<TBODY>
<TR>
<TD width=170><INPUT onclick=inputshift() type=checkbox name=shiftf>上檔功能 <INPUT onclick=inputshift() type=checkbox name=hypf>雙曲函數 </TD>
<TD><INPUT style="BACKGROUND-COLOR: lightgrey" readOnly size=3 name=bracket> <INPUT style="BACKGROUND-COLOR: lightgrey" readOnly size=3 name=memory> <INPUT style="BACKGROUND-COLOR: lightgrey" readOnly size=3 name=operator> </TD>
<TD width=183><INPUT style="COLOR: red" onclick=backspace() type=button value=" 退格 "> <INPUT style="COLOR: red" onclick="document.calc.display.value = 0 " type=button value=" 清屏 "> <INPUT style="COLOR: red" onclick=clearall() type=button value=" 全清"> </TD></TR></TBODY></TABLE>
<TABLE width=500>
<TBODY>
<TR>
<TD>
<TABLE>
<TBODY>
<TR align=middle>
<TD><INPUT style="COLOR: blue" onclick="inputfunction('pi','pi')" type=button value=" PI " name=pi> </TD>
<TD><INPUT style="COLOR: blue" onclick="inputfunction('e','e')" type=button value=" E " name=e> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputfunction('dms','deg')" type=button value=d.ms name=bt> </TD></TR>
<TR align=middle>
<TD><INPUT style="COLOR: #ff00ff" onclick=addbracket() type=button value=" ( "> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick=disbracket() type=button value=" ) "> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputfunction('ln','exp')" type=button value=" ln " name=ln> </TD></TR>
<TR align=middle>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputtrig('sin','arcsin','hypsin','ahypsin')" type=button value="sin " name=sin> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick="operation('^',7)" type=button value="x^y "> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputfunction('log','expdec')" type=button value="log " name=log> </TD></TR>
<TR align=middle>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputtrig('cos','arccos','hypcos','ahypcos')" type=button value="cos " name=cos> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputfunction('cube','cubt')" type=button value="x^3 " name=cube> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputfunction('!','!')" type=button value=" n! "> </TD></TR>
<TR align=middle>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputtrig('tan','arctan','hyptan','ahyptan')" type=button value="tan " name=tan> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputfunction('sqr','sqrt')" type=button value="x^2 " name=sqr> </TD>
<TD><INPUT style="COLOR: #ff00ff" onclick="inputfunction('recip','recip')" type=button value="1/x "> </TD></TR></TBODY></TABLE></TD>
<TD width=30></TD>
<TD>
<TABLE>
<TBODY>
<TR>
<TD><INPUT style="COLOR: red" onclick=putmemory() type=button value=" 儲存 "> </TD></TR>
<TR>
<TD><INPUT style="COLOR: red" onclick=getmemory() type=button value=" 取存 "> </TD></TR>
<TR>
<TD><INPUT style="COLOR: red" onclick=addmemory() type=button value=" 累存 "> </TD></TR>
<TR>
<TD><INPUT style="COLOR: red" onclick=multimemory() type=button value=" 積存 "> </TD></TR>
<TR>
<TD height=33><INPUT style="COLOR: red" onclick=clearmemory() type=button value=" 清存 "> </TD></TR></TBODY></TABLE></TD>
<TD width=30></TD>
<TD>
<TABLE>
<TBODY>
<TR align=middle>
<TD><INPUT style="COLOR: blue" onclick="inputkey('7')" type=button value=" 7 " name=k7> </TD>
<TD><INPUT style="COLOR: blue" onclick="inputkey('8')" type=button value=" 8 " name=k8> </TD>
<TD><INPUT style="COLOR: blue" onclick="inputkey('9')" type=button value=" 9 " name=k9> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('/',6)" type=button value=" / "> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('%',6)" type=button value=取余> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('&',3)" type=button value=" 與 "> </TD></TR>
<TR align=middle>
<TD><INPUT style="COLOR: blue" onclick="inputkey('4')" type=button value=" 4 " name=k4> </TD>
<TD><INPUT style="COLOR: blue" onclick="inputkey('5')" type=button value=" 5 " name=k5> </TD>
<TD><INPUT style="COLOR: blue" onclick="inputkey('6')" type=button value=" 6 " name=k6> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('*',6)" type=button value=" * "> </TD>
<TD><INPUT style="COLOR: red" onclick="inputfunction('floor','deci')" type=button value=取整 name=floor> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('|',1)" type=button value=" 或 "> </TD></TR>
<TR align=middle>
<TD><INPUT style="COLOR: blue" onclick="inputkey('1')" type=button value=" 1 "> </TD>
<TD><INPUT style="COLOR: blue" onclick="inputkey('2')" type=button value=" 2 " name=k2> </TD>
<TD><INPUT style="COLOR: blue" onclick="inputkey('3')" type=button value=" 3 " name=k3> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('-',5)" type=button value=" - "> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('<',4)" type=button value=左移> </TD>
<TD><INPUT style="COLOR: red" onclick="inputfunction('~','~')" type=button value=" 非 "> </TD></TR>
<TR align=middle>
<TD><INPUT style="COLOR: blue" onclick="inputkey('0')" type=button value=" 0 "> </TD>
<TD><INPUT style="COLOR: blue" onclick=changeSign() type=button value=+/-> </TD>
<TD><INPUT style="COLOR: blue" onclick="inputkey('.')" type=button value=" . " name=kp> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('+',5)" type=button value=" + "> </TD>
<TD><INPUT style="COLOR: red" onclick=result() type=button value=" = "> </TD>
<TD><INPUT style="COLOR: red" onclick="operation('x',2)" type=button value=異或> </TD></TR>
<TR align=middle>
<TD><INPUT style="COLOR: blue" disabled onclick="inputkey('a')" type=button value=" A " name=ka> </TD>
<TD><INPUT style="COLOR: blue" disabled onclick="inputkey('b')" type=button value=" B " name=kb> </TD>
<TD><INPUT style="COLOR: blue" disabled onclick="inputkey('c')" type=button value=" C " name=kc> </TD>
<TD><INPUT style="COLOR: blue" disabled onclick="inputkey('d')" type=button value=" D " name=kd> </TD>
<TD><INPUT style="COLOR: blue" disabled onclick="inputkey('e')" type=button value=" E" name=ke> </TD>
<TD><INPUT style="COLOR: blue" disabled onclick="inputkey('f')" type=button value=" F" name=kf> </TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></FORM></DIV><%referer=Request.ServerVariables ("HTTP_REFERER")%>
<!--結束 -->
❻ 編寫java application程序實現一個簡易計算器
Java計算器源代碼:
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
/**********************Java計算器主類*********************/
{
JFramef;
JMenumEdit;
JMenumView;
JMenumHelp;
JMenuItemmCopy;
JMenuItemmPaste;
JTextFieldtResult;
JButtonbNumber;
JButtonbOperator;
JButtonbOther;
JButtonbM;
booleanisDouble=false;//是否為實數
intopFlag=-1;
staticdoublet1=0,t2=0,t3=0,result=0;
staticintopflag1=-1,opflag2=-1,flag=0,resflag=1;
intpreOp,currentOp=0;//標准位
doubleop1=0,op2=0;//操作數
doublen3;
StringBufferbuf=newStringBuffer(20);
StringBufferBoard=newStringBuffer(20);//剪貼板
StringBuffermemory=newStringBuffer(20);//M系列
StringBufferstr=newStringBuffer();
//Java計算器構造器
publicSunnyCalculator()
{
f=newJFrame("Sunny計算器_楊梅樹的盔甲");
ContainercontentPane=f.getContentPane();
/**************************Java計算器菜單的創建*****************************/
JMenuBarmBar=newJMenuBar();
mBar.setOpaque(true);
mEdit=newJMenu("編輯(E)");
mEdit.setMnemonic(KeyEvent.VK_E);
mCopy=newJMenuItem("復制(C)");
mEdit.add(mCopy);
mPaste=newJMenuItem("粘貼(P)");
mEdit.add(mPaste);
mView=newJMenu("查看(V)");
mView.setMnemonic(KeyEvent.VK_V);
mView.add(newJMenuItem("標准型"));
mView.add(newJMenuItem("科學型"));
mView.addSeparator();
mView.add(newJMenuItem("查看分組"));
mHelp=newJMenu("幫助(H)");
mHelp.setMnemonic(KeyEvent.VK_H);
mHelp.add(newJMenuItem("幫助主題"));
mHelp.addSeparator();
mHelp.add(newJMenuItem("關於計算器"));
mBar.add(mEdit);
mBar.add(mView);
mBar.add(mHelp);
f.setJMenuBar(mBar);
contentPane.setLayout(newBorderLayout());
JPanelpTop=newJPanel();
tResult=newJTextField("0.",26);
tResult.setHorizontalAlignment(JTextField.RIGHT);
tResult.setEditable(false);
pTop.add(tResult);
contentPane.add(pTop,BorderLayout.NORTH);
JPanelpBottom=newJPanel();
pBottom.setLayout(newBorderLayout());
JPanelpLeft=newJPanel();
pLeft.setLayout(newGridLayout(5,1,3,3));
bM=newJButton("");
bM.setEnabled(false);
pLeft.add(bM);
/*************************Java計算器功能鍵定義***************************/
bOther=newJButton("MC");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,2,3,2));
pLeft.add(bOther);
bOther=newJButton("MR");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,2,3,2));
pLeft.add(bOther);
bOther=newJButton("MS");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,2,3,2));
pLeft.add(bOther);
bOther=newJButton("M+");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,2,3,2));
pLeft.add(bOther);
pBottom.add(pLeft,BorderLayout.WEST);
JPanelpRight=newJPanel();
pRight.setLayout(newBorderLayout());
JPanelpUp=newJPanel();
pUp.setLayout(newGridLayout(1,3,3,0));
bOther=newJButton("BackSpace");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
bOther.setMargin(newInsets(3,0,3,5));
pUp.add(bOther);
bOther=newJButton("CE");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
pUp.add(bOther);
bOther=newJButton("C");
bOther.addActionListener(this);
bOther.setForeground(Color.red);
pUp.add(bOther);
/***************************Java計算器數字鍵盤區定義**************************/
JPanelpDown=newJPanel();
pDown.setLayout(newGridLayout(4,5,3,2));
bNumber=newJButton("7");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("8");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("9");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bOperator=newJButton("/");
bOperator.setForeground(Color.red);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,0,3,0));
pDown.add(bOperator);
bOperator=newJButton("sqrt");
bOperator.addActionListener(this);
bOperator.setForeground(Color.red);
bOperator.setMargin(newInsets(3,0,3,0));
pDown.add(bOperator);
bNumber=newJButton("4");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
bNumber.setHorizontalTextPosition(JButton.LEFT);
pDown.add(bNumber);
bNumber=newJButton("5");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("6");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bOperator=newJButton("*");
bOperator.setForeground(Color.red);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton("%");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bNumber=newJButton("1");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("2");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bNumber=newJButton("3");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bOperator=newJButton("-");
bOperator.setForeground(Color.red);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton("1/x");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
pDown.add(bOperator);
bNumber=newJButton("0");
bNumber.setForeground(Color.blue);
bNumber.addActionListener(this);
bNumber.setMargin(newInsets(3,3,3,3));
pDown.add(bNumber);
bOperator=newJButton("+/-");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton(".");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton("+");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
bOperator=newJButton("=");
bOperator.setForeground(Color.blue);
bOperator.addActionListener(this);
bOperator.setMargin(newInsets(3,3,3,3));
pDown.add(bOperator);
pRight.add(pUp,BorderLayout.NORTH);
pRight.add(pDown,BorderLayout.SOUTH);
pBottom.add(pRight,BorderLayout.EAST);
contentPane.add(pBottom,BorderLayout.SOUTH);
f.setSize(newDimension(320,256));
f.setResizable(false);
f.setVisible(true);
f.addWindowListener(newWindowAdapter()
{
publicvoidwindowClosing(WindowEvente)
{
System.exit(0);
}
}
);
}
/************************Java計算器計算方法區***************************/
publicvoidactionPerformed(ActionEvente)
{
Strings=e.getActionCommand();
if(s.equals("復制(C)"))
{
Stringtemp=tResult.getText().trim();
Board.replace(0,Board.length(),temp);
mPaste.setEnabled(true);
}
elseif(s.equals("粘貼(p)"))
{
tResult.setText(Board.toString());
}
elseif(s.equals("CE"))
{
//如果是CE則清除文本框
tResult.setText("0.");
}
elseif(s.equals("BackSpace"))
{
if(!tResult.getText().trim().equals("0."))
{
//如果文本框中有內容
if(str.length()!=1&&str.length()!=0)
{
tResult.setText(str.delete(str.length()-1,str.length()).toString());
}
else
{
tResult.setText("0.");
str.setLength(0);
}
}
op2=Double.parseDouble(tResult.getText().trim());
}
elseif(s.equals("C"))
{
//如果是C刪除當前計算
tResult.setText("0.");
op1=op2=0;
str.replace(0,str.length(),"");
preOp=currentOp=0;
}
elseif(s.equals("MC"))
{
//如果是MC則清除緩沖區
Stringtemp="";
memory.replace(0,memory.length(),temp);
bM.setText("");
}
elseif(s.equals("MR"))
{
//如果按鍵為MR則恢復緩沖區的數到文本框
tResult.setText(memory.toString());
}
elseif(s.equals("MS"))
{
//如果按鍵為MS則將文本框的數存入緩沖區
Strings1=tResult.getText().trim();
memory.replace(0,memory.length(),s1);
bM.setText("M");
}
elseif(s.equals("M+"))
{
//如果按鍵為MS則將文本框值與緩沖區的數相加但不顯示結果
Stringtemp1=tResult.getText().trim();
doubledtemp=Double.parseDouble(temp1);
Stringtemp2=memory.toString();
dtemp+=Double.parseDouble(temp2);
temp1=String.valueOf(dtemp);
memory.replace(0,memory.length(),temp1);
}
elseif(s.equals("1/x"))
{
//如果按鍵為1/x則將文本框中的數據為它的倒數
Stringtemp=tResult.getText().trim();
doubledtemp=Double.parseDouble(temp);
tResult.setText(""+1/dtemp);
}
elseif(s.equals("sqrt"))
{
//如果按鍵為sqrt則將文本框中的內容求平方根
Stringtemp=tResult.getText().trim();
doubledtemp=Double.parseDouble(temp);
tResult.setText(""+Math.sqrt(dtemp));
}
elseif(s.equals("+"))
{
str.setLength(0);
if(currentOp==0)
{
preOp=currentOp=1;
op2=0;
tResult.setText(""+op1);
}
else
{
currentOp=preOp;
preOp=1;
switch(currentOp){
case1:
op1+=op2;
tResult.setText(""+op1);
break;
case2:
op1-=op2;
tResult.setText(""+op1);
break;
case3:
op1*=op2;
tResult.setText(""+op1);
break;
case4:
op1/=op2;
tResult.setText(""+op1);
break;
}
}
}
elseif(s.equals("-")){
str.setLength(0);
if(currentOp==0)
{
preOp=currentOp=2;//op1=op2;op2=0;
tResult.setText(""+op1);
}
else
{
currentOp=preOp;
preOp=2;
switch(currentOp){
case1:op1=op1+op2;tResult.setText(""+op1);break;
case2:op1=op1-op2;tResult.setText(""+op1);break;
case3:op1=op1*op2;tResult.setText(""+op1);break;
case4:op1=op1/op2;tResult.setText(""+op1);break;
}
}
}
elseif(s.equals("*"))//*
{
str.setLength(0);
if(currentOp==0)
{
preOp=currentOp=3;//op1=op2;op2=1;
tResult.setText(""+op1);//op1=op2;
}
else
{
currentOp=preOp;
preOp=3;
switch(currentOp){
case1:op1=op1+op2;tResult.setText(""+op1);break;
case2:op1=op1-op2;tResult.setText(""+op1);break;
case3:op1=op1*op2;tResult.setText(""+op1);break;
case4:op1=op1/op2;tResult.setText(""+op1);break;
}
}
}
elseif(s.equals("/"))///
{
str.setLength(0);
if(currentOp==0)
{
preOp=currentOp=4;//op2=1;
tResult.setText(""+op1);//op1=op2;
}
else
{
currentOp=preOp;
preOp=4;
switch(currentOp){
case1:op1=op1+op2;tResult.setText(""+op1);break;
case2:op1=op1-op2;tResult.setText(""+op1);break;
case3:op1=op1*op2;tResult.setText(""+op1);break;
case4:op1=op1/op2;tResult.setText(""+op1);break;
}
}
}
elseif(s.equals("="))//=
{
if(currentOp==0)
{
str.setLength(0);
tResult.setText(""+op2);
}
else
{
str.setLength(0);
currentOp=preOp;
switch(currentOp){
case1:op1=op1+op2;tResult.setText(""+op1);break;
case2:op1=op1-op2;tResult.setText(""+op1);break;
case3:op1=op1*op2;tResult.setText("&qu
❼ 如何用JAVA語言編寫計算器小程序
具體代碼如下:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Calculator extends JFrame implements ActionListener {
private JFrame jf;
private JButton[] allButtons;
private JButton clearButton;
private JTextField jtf;
public Calculator() {
//對圖形組件實例化
jf=new JFrame("任靜的計算器1.0:JAVA版");
jf.addWindowListener(new WindowAdapter(){
public void windowClosing(){
System.exit(0);
}
});
allButtons=new JButton[16];
clearButton=new JButton("清除");
jtf=new JTextField(25);
jtf.setEditable(false);
String str="123+456-789*0.=/";
for(int i=0;i<allButtons.length;i++){
allButtons[i]=new JButton(str.substring(i,i+1));
}
}
public void init(){
//完成布局
jf.setLayout(new BorderLayout());
JPanel northPanel=new JPanel();
JPanel centerPanel=new JPanel();
JPanel southPanel=new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(jtf);
for(int i=0;i<16;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
jf.add(northPanel,BorderLayout.NORTH);
jf.add(centerPanel,BorderLayout.CENTER);
jf.add(southPanel,BorderLayout.SOUTH);
addEventHandler();
}
//添加事件監聽
public void addEventHandler(){
jtf.addActionListener(this);
for(int i=0;i<allButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Calculator.this.jtf.setText("");
}
});
}
//事件處理
public void actionPerformed(ActionEvent e) {
//在這里完成事件處理 使計算器可以運行
String action=e.getActionCommand();
if(action=="+"||action=="-"||action=="*"||action=="/"){
}
}
public void setFontAndColor(){
Font f=new Font("宋體",Font.BOLD,24);
jtf.setFont(f);
jtf.setBackground(new Color(0x8f,0xa0,0xfb));
for(int i=0;i<16;i++){
allButtons[i].setFont(f);
allButtons[i].setForeground(Color.RED);
}
}
public void showMe(){
init();
setFontAndColor();
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new Calculator().showMe();
}
}
❽ 用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:編寫一個計算器小程序,要求可以做加減乘除運算
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
private static final long serialVersionUID = 8199443193151152362L;
private JButton bto_s=new JButton("sqrt"),bto_zf=new JButton("+/-"),bto_ce=new JButton("CE"),bto_c=new JButton("C"),bto_7=new JButton("7"),
bto_8=new JButton("8"),bto_9=new JButton("9"),bto_chu=new JButton("/"),bto_4=new JButton("4"),bto_5=new JButton("5"),
bto_6=new JButton("6"),bto_cheng=new JButton("*"),bto_1=new JButton("1"),bto_2=new JButton("2"),bto_3=new JButton("3"),
bto_jian=new JButton("-"),bto_0=new JButton("0"),bto_dian=new JButton("."),bto_deng=new JButton("="),bto_jia=new JButton("+");
JButton button[]={bto_s,bto_zf,bto_ce,bto_c,bto_7,bto_8,bto_9,bto_chu,bto_4,bto_5,bto_6,bto_cheng,bto_1,bto_2,bto_3,bto_jian,
bto_0,bto_dian,bto_deng,bto_jia};
private JTextField text_double;// = new JTextField("0");
private String operator = "="; //當前運算的運算符
private boolean firstDigit = true; // 標志用戶按的是否是整個表達式的第一個數字,或者是運算符後的第一個數字
private double resultNum = 0.0; // 計算的中間結果
private boolean operateValidFlag = true; //判斷操作是否合法
public Calculator()
{
super("Calculator");
this.setBounds(300, 300, 300, 300);
this.setResizable(false);
this.setBackground(Color.orange);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());//設置布局
text_double=new JTextField("0",20);//設置文本區
text_double.setHorizontalAlignment(JTextField.RIGHT);//設置水平對齊方式未右對齊
this.getContentPane().add(text_double,BorderLayout.NORTH);//將文本區添加到Content北部
JPanel panel=new JPanel(new GridLayout(5,4));//在內容窗口添加一個網格布局
this.getContentPane().add(panel);//添加panel面板
for(int i=0;i<button.length;i++)//在面板上添加按鈕
panel.add(button[i]);
for(int i=0;i<button.length;i++)
button[i].addActionListener(this);//為按鈕注冊
text_double.setEditable(false);//文本框不可編輯
text_double.addActionListener(this);//
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)//
{
String c= e.getActionCommand();//返回與此動作相關的命令字元串。
System.out.println("##########command is "+c);
if(c.equals("C")){
handleC(); //用戶按了「C」鍵
}
else if (c.equals("CE")) // 用戶按了"CE"鍵
{
text_double.setText("0");
}
else if ("0123456789.".indexOf(c) >= 0) // 用戶按了數字鍵或者小數點鍵
{
handleNumber(c); // handlezero(zero);
} else //用戶按了運算符鍵
{
handleOperator(c);
}
}
private void handleC() // 初始化計算器的各種值
{
text_double.setText("0");
firstDigit = true;
operator = "=";
}
private void handleNumber(String button) {
if (firstDigit)//輸入的第一個數字
{
text_double.setText(button);
} else if ((button.equals(".")) && (text_double.getText().indexOf(".") < 0))//輸入的是小數點,並且之前沒有小數點,則將小數點附在結果文本框的後面
//如果字元串參數作為一個子字元串在此對象中出現,則返回第一個這種子字元串的第一個字元的索引;如果它不作為一個子字元串出現,則返回 -1
{
text_double.setText(text_double.getText() + ".");
} else if (!button.equals("."))// 如果輸入的不是小數點,則將數字附在結果文本框的後面
{
text_double.setText(text_double.getText() + button);
}
// 以後輸入的肯定不是第一個數字了
firstDigit = false;
}
private void handleOperator(String button) {
if (operator.equals("/")) {
// 除法運算
// 如果當前結果文本框中的值等於0
if (getNumberFromText() == 0.0){
// 操作不合法
operateValidFlag = false;
text_double.setText("除數不能為零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("+")){
// 加法運算
resultNum += getNumberFromText();
} else if (operator.equals("-")){
// 減法運算
resultNum -= getNumberFromText();
} else if (operator.equals("*")){
// 乘法運算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
// 平方根運算
if(getNumberFromText()<0){
operateValidFlag = false;
text_double.setText("被開方數不能為負數");}
else
resultNum = Math.sqrt(resultNum);
}
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) {
text_double.setText(String.valueOf(t1));
} else {
text_double.setText(String.valueOf(resultNum));
}
}
operator = button; //運算符等於用戶按的按鈕
firstDigit = true;
operateValidFlag = true;
}
private double getNumberFromText() //從結果的文本框獲取數字
{
double result = 0;
try {
result = Double.valueOf(text_double.getText()).doubleValue(); // ValueOf()返回表示指定的 double 值的 Double 實例
} catch (NumberFormatException e){
}
return result;
}
public static void main(final String[] args) {
new Calculator();
}
}
❿ java編寫一個小型計算器應用程序
package 計算器;
import java.awt.*;
import java.awt.event.*;
public class computer implements WindowListener,ActionListener{
private Frame f;
double d0,d1,d2,result;
boolean flag=true;
String s,oper;
TextField tf1;
Panel p=new Panel();
public static void main(String args[])
{ computer e=new computer();
e.go();
}
public void go(){
int i;
result=0;
s=new String();
oper=new String("+");
f=new Frame("計算器");
MenuBar mb=new MenuBar();
f.setMenuBar(mb);
Menu m1=new Menu("編輯");
Menu m2=new Menu("幫助");
Menu m3=new Menu("關於");
mb.add(m1);
mb.add(m3);
mb.setHelpMenu(m2);
tf1=new TextField("",15);
Button[] b=new Button[21];
for(i=1;i<21;i++)
{
b[i]=new Button();
b[i].setFont(new Font("仿宋",0,16));
}
b[1].setLabel("退格");
b[2].setLabel("CE");
b[3].setLabel("C");
b[4].setLabel("/");
b[5].setLabel("7");
b[6].setLabel("8");
b[7].setLabel("9");
b[8].setLabel("*");
b[9].setLabel("4");
b[10].setLabel("5");
b[11].setLabel("6");
b[12].setLabel("-");
b[13].setLabel("1");
b[14].setLabel("2");
b[15].setLabel("3");
b[16].setLabel("+");
b[17].setLabel("0");
b[18].setLabel("+/-");
b[19].setLabel(".");
b[20].setLabel("=");
p.setLayout(new GridLayout(5,4));
p.setBackground(new Color(80,30,100));
for(i=1;i<21;i++)
{ p.add(b[i]);
b[i].addActionListener(this);
b[i].setBackground(new Color(20,130,180));
b[i].setForeground(Color.yellow);
}
for(i=1;i<4;i++)
{
b[i].setBackground(new Color(120,180,170));
b[i].setForeground(Color.blue);
}
for(i=1;i<=4;i++)
{ b[i*4].setBackground(new Color(120,180,170));
b[i*4].setForeground(Color.red);
}
b[20].setBackground(Color.red);
f.addWindowListener(this);
f.setLayout(new BorderLayout());
f.add("North",tf1);
f.add("Center",p);
f.setSize(200,200);
f.setVisible(true);
}
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){}
public void actionPerformed(ActionEvent e){
String i1=tf1.getText();
s=e.getActionCommand();
if(s=="0"| s=="1"|s=="2"|s=="3"|s=="4"|s=="5"|s=="6"|s=="7"|s=="8"|s=="9"|s==".")
{ if(flag) tf1.setText(i1+s);
else
{ tf1.setText(s);
flag=true;
}
}
else if(s=="+"|s=="-"|s=="*"|s=="/")
{ result=Double.parseDouble(i1);
flag=false;
oper=s;
}
else if(s=="=")
{ d0=Double.parseDouble(i1);
if(oper=="+") result+=d0;
if(oper=="-") result-=d0;
if(oper=="*") result*=d0;
if(oper=="/") result/=d0;
tf1.setText(Double.toString(result));
flag=false;
}
else if(s=="CE")
{ tf1.setText("");
flag=false;
}
else if(s=="C")
{ result=0;
tf1.setText("");
flag=false;
}
else if(s=="退格")
{ String ss=tf1.getText();
int i=ss.length();
ss=ss.substring(0,i-1);
tf1.setText(ss);
}
else if(s=="+/-")
{ d2=-1*Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(d2));
}
}
}
絕對能運行