㈠ java設計計算器
packagecn.hnpi;
importjava.awt.BorderLayout;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
{
JButtonb0=newJButton("0");
JButtonb1=newJButton("1");
JButtonb2=newJButton("2");
JButtonb3=newJButton("3");
JButtonb4=newJButton("4");
JButtonb5=newJButton("5");
JButtonb6=newJButton("6");
JButtonb7=newJButton("7");
JButtonb8=newJButton("8");
JButtonb9=newJButton("9");
JButtonjiaButton=newJButton("+");
JButtonjianButton=newJButton("-");
JButtonchengButton=newJButton("*");
JButtonchuButton=newJButton("/");
JButtonyuButton=newJButton("%");
JButtonjjButton=newJButton("+/-");
JButtonsqrtButton=newJButton("sqrt");
JButtondianButton=newJButton(".");
JButtondengButton=newJButton("=");
JButtonButton=newJButton("1/x");
JButtonbackButton=newJButton("Backpace");
JButtoncButton=newJButton("C");
publicdoubleop1;
publicdoubleop2;
publicstaticfinalintJIA=0;
publicstaticfinalintJIAN=1;
publicstaticfinalintCHENG=2;
publicstaticfinalintCHU=3;
publicstaticfinalintJJ=4;
publicstaticfinalintDIAN=5;
publicintcurrent0p=0;
privatebooleanopEnd=false;
JPanelpanel1=newJPanel();
JPanelpanel2=newJPanel();
JPanelpanel3=newJPanel();
JPanelpanel4=newJPanel();
JTextFieldresult=newJTextField(20);
publicCalculator(){
initPanel2();
initPanel3();
panel2.setLayout(newGridLayout(5,4));
panel1.setLayout(newBorderLayout());
panel1.add(panel3,BorderLayout.NORTH);//設置位置
panel1.add(panel2,BorderLayout.CENTER);//設置位置
getContentPane().add(panel1);
addActionListeners();
setSize(260,260);
setLocation(500,300);
setVisible(true);
setDefaultCloseOperation(Calculator.EXIT_ON_CLOSE);
this.setResizable(false);
this.setTitle("計算器");
}
privatevoidinitPanel2(){
//把組件添加到相應的panel上
panel2.add(b7);
panel2.add(b8);
panel2.add(b9);
panel2.add(chuButton);
panel2.add(b4);
panel2.add(b5);
panel2.add(b6);
panel2.add(chengButton);
panel2.add(b1);
panel2.add(b2);
panel2.add(b3);
panel2.add(jianButton);
panel2.add(b0);
panel2.add(jjButton);
panel2.add(dianButton);
panel2.add(jiaButton);
panel2.add(Button);
panel2.add(yuButton);
panel2.add(sqrtButton);
panel2.add(dengButton);
}
privatevoidaddActionListeners(){
ActionHandlerc=newActionHandler();
b0.addActionListener(c);
b1.addActionListener(c);
b2.addActionListener(c);
b3.addActionListener(c);
b4.addActionListener(c);
b5.addActionListener(c);
b6.addActionListener(c);
b7.addActionListener(c);
b8.addActionListener(c);
b9.addActionListener(c);
jiaButton.addActionListener(c);
dengButton.addActionListener(c);
chengButton.addActionListener(c);
chuButton.addActionListener(c);
jianButton.addActionListener(c);
jjButton.addActionListener(c);
dianButton.addActionListener(c);
sqrtButton.addActionListener(c);
yuButton.addActionListener(c);
Button.addActionListener(c);
backButton.addActionListener(c);
cButton.addActionListener(c);
}
{
publicvoidactionPerformed(ActionEvente){
if(e.getSource()==b0){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"0");
}
if(e.getSource()==b1){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"1");
opEnd=true;
}
if(e.getSource()==b2){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"2");
opEnd=true;
}
if(e.getSource()==b3){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"3");
opEnd=true;
}
if(e.getSource()==b4){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"4");
opEnd=true;
}
if(e.getSource()==b5){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"5");
opEnd=true;
}
if(e.getSource()==b6){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"6");
opEnd=true;
}
if(e.getSource()==b7){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"7");
opEnd=true;
}
if(e.getSource()==b8){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"8");
opEnd=true;
}
if(e.getSource()==b9){
if(opEnd==false){
result.setText("");
}
result.setText(result.getText()+"9");
opEnd=true;
}
try{
if(e.getSource()==jiaButton){
op1=Double.parseDouble(result.getText());
//2、說明操作數已經輸入完畢
opEnd=false;
current0p=JIA;
}
if(e.getSource()==chengButton){
op1=Double.parseDouble(result.getText());
//2、說明操作數已經輸入完畢
opEnd=false;
current0p=CHENG;
}
if(e.getSource()==chuButton){
op1=Double.parseDouble(result.getText());
//2、說明操作數已經輸入完畢
opEnd=false;
current0p=CHU;
}
if(e.getSource()==jianButton){
op1=Double.parseDouble(result.getText());
//2、說明操作數已經輸入完畢
opEnd=false;
current0p=JIAN;
}
if(e.getSource()==jjButton){
Stringtmp=result.getText();
if(tmp.equals("")||tmp.equals("0")){
return;
}
if(tmp.charAt(0)=='-'){
tmp=tmp.substring(1);
}else{
tmp='-'+tmp;
}
result.setText(tmp);
}
if(e.getSource()==dianButton){
Stringtmp=result.getText();
if(tmp.equals("")){
return;
}
if(tmp.indexOf(".")!=-1){
return;
}
tmp=tmp+".";
result.setText(tmp);
}
if(e.getSource()==sqrtButton){
Stringtmp=result.getText();
if(tmp.equals("")){
return;
}
doubled;
d=Double.parseDouble(tmp);//先定義一個double類型的d
if(d<0){
result.setText("不能對負數求平方根!");
return;
}
op2=Math.sqrt(d);
result.setText(op2+"");
}
if(e.getSource()==backButton){
Strings=result.getText();
result.setText("");
for(inti=0;i<s.length()-1;i++){
chara=s.charAt(i);
result.setText(result.getText()+a);
}
}
if(e.getSource()==cButton){
result.setText("0");
opEnd=false;
}
if(e.getSource()==dengButton){
op2=Double.parseDouble(result.getText());
switch(current0p){
caseJIA:
result.setText(op1+op2+"");
break;
caseJIAN:
result.setText(op1-op2+"");
break;
caseCHENG:
result.setText(op1*op2+"");
break;
caseCHU:
if(op2==0){
result.setText("被除數不能為零!");
break;
}
result.setText(op1/op2+"");
break;
}
opEnd=false;
}
}catch(Exceptione1){
result.setText("Wrong");
opEnd=false;
}
}
}
privatevoidinitPanel3(){
panel3.setLayout(newGridLayout(2,1));
panel3.add(result);
panel3.add(panel4);
panel4.setLayout(newGridLayout(1,2));
panel4.add(backButton);
panel4.add(cButton);
//panel3.setPreferredSize(newDimension(260,65));
}
publicstaticvoidmain(String[]args){
Calculatorc=newCalculator();//生成類的實例
}
}
㈡ JAVA課程設計天數計算器(輸入年月日等到是當年的第幾天)Would文檔
//你試試這個能不能實現
importjava.io.*;
publicclassDateCal{
staticpublicvoidmain(String[]args){
intyear,month,day;
intdays=0;
booleanluinian=false;
System.out.print("inputtheyear:");
year=IO.getInt();
System.out.print("inputthemonth:");
month=IO.getInt();
System.out.print("inputtheday:");
day=IO.getInt();
if(year%400==0||(year%4==0&&year%100!=0)){
luinian=true;
}
for(inti=1;i<month;i++){
switch(i){
case1:
case3:
case5:
case7:
case8:
case10:
case12:
days+=31;
break;
case2:
days+=28;
break;
case4:
case6:
case9:
case11:
days+=30;
break;
}
}
if(luinian&&month>2){
days++;
}
days+=day;
System.out.println(year+"年"+month+"月"+day+"日是"+year+"的第"
+days+"天");
}
}
classIO{
publicstaticintgetInt(){
DataInputStreamdis=newDataInputStream(System.in);
intvalue=0;
try{
@SuppressWarnings("deprecation")
Stringstr=dis.readLine();
value=Integer.parseInt(str);
}catch(IOExceptione){
e.printStackTrace();
}
returnvalue;
}
}
㈢ Java設計計算器
****************************************************************
寫了一天,終於寫完了。
****************************************************************
說明:
類Calc.java出了界面符合你的要求外,還有以下優點:
1.對輸入內容進行校驗,如果是非法字元(如字母),不響應鍵盤事件,而且單個文本框只能輸入一個小數點;
2.使用Windows界面風格;
3.採用大數計算,更精準;
4.其它……
****************************************************************
代碼如下:
****************************************************************
importjava.awt.BorderLayout;
importjava.awt.Dimension;
importjava.awt.FlowLayout;
importjava.awt.Toolkit;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.event.KeyAdapter;
importjava.awt.event.KeyEvent;
importjava.math.BigDecimal;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JMenu;
importjavax.swing.JMenuBar;
importjavax.swing.JMenuItem;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
importjavax.swing.UIManager;
/**
*@authorGodwin
*@version2010-05-16
*/
{
JTextFieldnumber1Text;
JTextFieldnumber2Text;
JTextFieldresultText;
publicCalc(){
this.setTitle("計算器");
/*
*菜單欄
*/
//Operation菜單
JMenuItemaddMenuItem=newJMenuItem("Add");
addMenuItem.setMnemonic('a');
JMenuItemsubtractMenuItem=newJMenuItem("Subtract");
subtractMenuItem.setMnemonic('s');
JMenuItemmultiplyMenuItem=newJMenuItem("Multiply");
multiplyMenuItem.setMnemonic('m');
JMenuItemdivideMenuItem=newJMenuItem("Divide");
divideMenuItem.setMnemonic('d');
JMenuoperationFile=newJMenu("Operation");
operationFile.setMnemonic('o');
operationFile.add(addMenuItem);
operationFile.add(subtractMenuItem);
operationFile.add(multiplyMenuItem);
operationFile.add(divideMenuItem);
//Exit菜單
JMenuexitMenu=newJMenu("Exit");
exitMenu.setMnemonic('x');
JMenuItemexitItem=newJMenuItem("Exit");
exitItem.setMnemonic('x');
exitItem.addActionListener(newExitActionListener());
exitMenu.add(exitItem);
//添加Operation和Exit菜單
JMenuBarmenubar=newJMenuBar();
menubar.add(operationFile);
menubar.add(exitMenu);
/*
*操作數和結果
*/
JLabelnumber1Label=newJLabel("Number1");
number1Text=newJTextField(6);
JLabelnumber2Label=newJLabel("Number2");
number2Text=newJTextField(6);
JLabelresultLabel=newJLabel("Result");
resultText=newJTextField(10);
resultText.setEditable(false);
JPaneloperandPanel=newJPanel(newFlowLayout());
operandPanel.add(number1Label);
operandPanel.add(number1Text);
operandPanel.add(number2Label);
operandPanel.add(number2Text);
operandPanel.add(resultLabel);
operandPanel.add(resultText);
/*
*操作符
*/
JButtonaddButton=newJButton("Add");
JButtonsubtractButton=newJButton("Subtract");
JButtonmultiplyButton=newJButton("Multiply");
JButtondivideButton=newJButton("Divide");
JPaneloperatorPanel=newJPanel(newFlowLayout());
operatorPanel.add(addButton);
operatorPanel.add(subtractButton);
operatorPanel.add(multiplyButton);
operatorPanel.add(divideButton);
/*
*添加所有面板
*/
this.add(menubar,BorderLayout.NORTH);
this.add(operandPanel,BorderLayout.CENTER);
this.add(operatorPanel,BorderLayout.SOUTH);
this.pack();
this.setResizable(false);
Toolkittool=Toolkit.getDefaultToolkit();
Dimensionscreen=tool.getScreenSize();
this.setLocation(screen.width/2-this.getWidth()/2,screen.height
/2-this.getHeight()/2);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*
*添加事件監聽
*/
//菜單監聽
addMenuItem.addActionListener(this);
subtractMenuItem.addActionListener(this);
multiplyMenuItem.addActionListener(this);
divideMenuItem.addActionListener(this);
//文本框監聽
number1Text.addKeyListener(newVerifyInputKeyAdapter());
number2Text.addKeyListener(newVerifyInputKeyAdapter());
//按鈕監聽
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
}
{
publicvoidkeyTyped(KeyEvente){
charc=e.getKeyChar();
System.out.println(c);
if(!(('0'<=c)&&(c<='9')||(c==KeyEvent.VK_DELETE)||(c==KeyEvent.VK_BACK_SPACE))){
if(!((!((JTextField)(e.getSource())).getText().contains("."))&&(c=='.'))){
e.consume();
}
}
}
}
{
publicvoidactionPerformed(ActionEvente){
System.exit(0);
}
}
publicvoidactionPerformed(ActionEvente){
Stringoperand1=number1Text.getText();
BigDecimalbig1=BigDecimal.valueOf(Double.valueOf(operand1));
Stringoperand2=number2Text.getText();
BigDecimalbig2=BigDecimal.valueOf(Double.valueOf(operand2));
if((!(operand1.equals("")))&&(operand1!=null)
&&(!(operand2.equals("")))&&(operand2!=null)){
Stringname=e.getSource().getClass().getSimpleName();
Stringoperator="";
if(name.equals("JButton")){
JButtonb=(JButton)(e.getSource());
operator=b.getText();
}elseif(name.equals("JMenuItem")){
JMenuItemm=(JMenuItem)e.getSource();
operator=m.getText();
}
if(operator.equals("Add")){
resultText.setText(String.valueOf(big1.add(big2)));
}elseif(operator.equals("Subtract")){
resultText.setText(String.valueOf(big1.subtract(big2)));
}elseif(operator.equals("Multiply")){
resultText.setText(String.valueOf(big1.multiply(big2)));
}elseif(operator.equals("Divide")){
resultText.setText(String.valueOf(big1.divide(big2)));
}else{
JOptionPane.showMessageDialog(this,"操作有誤!","錯誤提示",
JOptionPane.WARNING_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(this,"請輸入操作數!","錯誤提示",
JOptionPane.WARNING_MESSAGE);
number1Text.requestFocus();
}
}
publicstaticvoidmain(String[]args)throwsException{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
newCalc();
}
}
****************************************************************
運行結果如下:
㈣ java 計算器課程設計報告
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;//導包
class MyClass extends JFrame
//創建一個MyClass類繼承JFrame框架的窗口類,
//也就是說JFrame里有的功能MyClass都能實現
{
JLabel a1=new JLabel("第一個數");
//創建一個顯示「第一個數」的標簽
JLabel a2=new JLabel("第二個數");
JLabel a3=new JLabel("運算結果");
JTextField b1=new JTextField(5);
//創建一個文本框、默認長度為5,用來輸入運算數字,當然也可以默認為空
JTextField b2=new JTextField(5);
JTextField b3=new JTextField(5);
//創建一個用於顯示運算結果的標簽,也可以創建一個標簽來顯示
JButton a=new JButton("加");
//創建一個用於加法計算的按鈕,點擊時進行加法運算
JButton b=new JButton("減");
JButton c=new JButton("乘");
JButton d=new JButton("除");
JPanel jp1=new JPanel();//創建一個面板,用來放控制項
JPanel jp2=new JPanel();
JPanel jp3=new JPanel();
MyClass()//構造函數,用來初始化的
{
setLayout(new GridLayout(3,1));//添加一個四行四列的布局管理器
jp1.setLayout(new FlowLayout());//設置JP1面板為流式布局管理器
jp1.setLayout(new FlowLayout());
//將a1,b1,a2,b2四個控制項添加到jp1面板中
jp1.add(a1);
jp1.add(b1);
jp1.add(a2);
jp1.add(b2);
jp1.add(a3);
//將a,b,c,d四個控制項添加到jp2面板中
jp2.add(a);
jp2.add(b);
jp2.add(c);
jp2.add(d);
jp3.add(a3);
jp3.add(b3);
//將jp1,jp2,jp3三個面板添加到窗口中
add(jp1);
add(jp3);
add(jp2);
Object e;
a.addActionListener(new ActionListener()
//創建一個匿名的事件監聽器
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
double x=Double.valueOf(b1.getText().toString());
//獲取第一個輸入數,並將其由String型轉換成double型
double y=Double.valueOf(b2.getText().toString());
//獲取第二個輸入數,並將其由String型轉換成double型
b3.setText(""+(x+y));
//將運算結果在b3這個文本框中顯示
}
});
b.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
double x=Double.valueOf(b1.getText().toString());
double y=Double.valueOf(b2.getText().toString());
b3.setText(""+(x-y));
}
});
c.addActionListener(new ActionListener()//創建一個匿名的事件監聽器
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
double x=Double.valueOf(b1.getText().toString());
double y=Double.valueOf(b2.getText().toString());
b3.setText(""+(x*y));
}
});
d.addActionListener(new ActionListener()//創建一個匿名的事件監聽器
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
double x=Double.valueOf(b1.getText().toString());
double y=Double.valueOf(b2.getText().toString());
//因為0不能做除數,所以在這里需要進行判斷
if(y==0)
{
b3.setText("錯誤");
}
else
{
b3.setText(""+(x/y));
}
}
});
//下面的是設置窗口的屬性
this.setTitle("計算器");//設置窗口的標題
//this.setSize(400,400);//設置窗口的大小,也可以改成this.pack()
this.pack();
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);//設置關閉屬性
this.setVisible(true);//設置窗口的可見性
}
public static void main(String[] args)//主函數
{
new MyClass();
}
}
㈤ 跪求java課程設計報告!要求:編寫一個類似於windows計算器的程序,能實現加減乘除等基本運算並能處理異常
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class Jisuan extends JFrame implements ActionListener{
private JTextField reasult;
private JButton btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btn0,
btnAC,btnAdd,btnSub,btnReasult,btnD,
btnAbout,btnCancel;
private boolean add,sub,end,s,c;
private String str;
private double num1,num2;
public Jisuan(){
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
TitledBorder tb=new TitledBorder("輸出"); tb.setTitleColor(Color.BLUE);
btnAbout=new JButton(" 關於 ");
btnCancel=new JButton("Cancel");
btnCancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ee)
{
System.exit(0);
}
});
btnAbout.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ee)
{
JOptionPane.showMessageDialog(null,"無",
"消息",JOptionPane.INFORMATION_MESSAGE);
}
});
p3.add(btnAbout);
p3.add(btnCancel);
//JPanel p4=new JPanel();
//JPanel p5=new JPanel();
//reasult.setBorder(tb);
reasult =new JTextField("0",20);
reasult.setEditable(false);
reasult.setHorizontalAlignment(JTextField.RIGHT);
reasult.setForeground(Color.BLUE);
p1.setBorder(tb);
p1.add(reasult);
btn0=new JButton("0"); btn0.addActionListener(this);
btn1=new JButton("1"); btn1.addActionListener(this);
btn2=new JButton("2"); btn2.addActionListener(this);
btn3=new JButton("3"); btn3.addActionListener(this);
btn4=new JButton("4"); btn4.addActionListener(this);
btn5=new JButton("5"); btn5.addActionListener(this);
btn6=new JButton("6"); btn6.addActionListener(this);
btn7=new JButton("7"); btn7.addActionListener(this);
btn8=new JButton("8"); btn8.addActionListener(this);
btn9=new JButton("9"); btn9.addActionListener(this);
btnD=new JButton("."); btnD.addActionListener(this); btnD.setForeground(Color.RED);
btnAC=new JButton("AC"); btnAC.addActionListener(this); btnAC.setBackground(Color.PINK);
btnAdd=new JButton("+"); btnAdd.addActionListener(this); btnAdd.setForeground(Color.BLUE);
btnSub=new JButton("—"); btnSub.addActionListener(this); btnSub.setForeground(Color.BLUE);
btnReasult=new JButton("="); btnReasult.addActionListener(this); btnReasult.setForeground(Color.RED);
p2.add(btn1);p2.add(btn2);p2.add(btn3);p2.add(btn4);p2.add(btn5);
p2.add(btn6);p2.add(btn7);p2.add(btn8);p2.add(btn9);p2.add(btn0);
p2.add(btnD);p2.add(btnAC);p2.add(btnAdd);p2.add(btnSub);p2.add(btnReasult);
p2.setLayout(new GridLayout(5,3));
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);
add(p3,BorderLayout.SOUTH);
}
public void num(int i){
String s = null;
s=String.valueOf(i);
if(end){
//如果數字輸入結束,則將文本框置零,重新輸入
reasult.setText("0");
end=false;
}
if((reasult.getText()).equals("0")){
//如果文本框的內容為零,則覆蓋文本框的內容
reasult.setText(s);
}
else{
//如果文本框的內容不為零,則在內容後面添加數字
str = reasult.getText() + s;
reasult.setText(str);
}
}/*
String s=null;
s=String.valueOf(i);
str=reasult.getText()+s;
reasult.setText(str);
}*/
public void actionPerformed(ActionEvent e){
if(e.getSource()==btn1)
num(1);
else if(e.getSource()==btn2)
num(2);
else if(e.getSource()==btn3)
num(3);
else if(e.getSource()==btn4)
num(4);
else if(e.getSource()==btn5)
num(5);
else if(e.getSource()==btn6)
num(6);
else if(e.getSource()==btn7)
num(7);
else if(e.getSource()==btn8)
num(8);
else if(e.getSource()==btn9)
num(9);
else if(e.getSource()==btn0)
num(0);
else if(e.getSource()==btnAdd){
sign(1);
btnD.setEnabled(true);
}
else if(e.getSource()==btnSub){
sign(2);
btnD.setEnabled(true);
}
else if(e.getSource()==btnAC){
btnD.setEnabled(true);
reasult.setText("0");
}
else if(e.getSource()==btnD){
str=reasult.getText();
str+=".";
reasult.setText(str);
btnD.setEnabled(false);
}
else if(e.getSource()==btnReasult){
btnD.setEnabled(true);
num2=Double.parseDouble(reasult.getText());
if(add){
num1=num1 + num2;}
else if(sub){
num1=num1 - num2;}
reasult.setText(String.valueOf(num1));
end=true;
}
}
public void sign(int s){
if(s==1){
add=true;
sub=false;
}
else if(s==2){
add=false;
sub=true;
}
num1=Double.parseDouble(reasult.getText());
end=true;
}
public static void main(String[] args){
Jisuan j=new Jisuan();
j.setTitle("+/-簡易計算器");
j.setLocation(500,280);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setResizable(false);
j.pack();
j.setVisible(true);
}
}
沒寫乘法,你自其實從網上搜索就能搜出來現成代碼
㈥ java簡單計算器實驗報告
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class 計算器 extends JFrame implements ActionListener {
private final String[] KEYS = { "7", "8", "9", "÷", "sqrt", "4", "5", "6",
"×", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
private final String[] COMMAND = { "Backspace", "CE", "C" };
private final String[] M = { " ", "MC", "MR", "MS", "M+" };
private JButton keys[] = new JButton[KEYS.length];
private JButton commands[] = new JButton[COMMAND.length];
private JButton m[] = new JButton[M.length];
private JTextField resultText = new JTextField();
private boolean firstDigit = true;
private double resultNum = 0.0;
private String operator = "=";
static double mr;// 記憶的數字
private boolean operateValidFlag = true;
JPanel panel[]=new JPanel[4];
public 計算器(){
super("計算器");
init();
setBackground(Color.LIGHT_GRAY);
setResizable(false);
setLocation(588, 250);
setSize(378,214);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); //窗口不能直接關閉
setVisible(true);
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e){
if (JOptionPane.showConfirmDialog(null,"確定退出? ", "提示",2)==0){
System.exit(0);
}}});
}
private void init() {
setLayout(null);
for (int i = 0; i < 4; i++) {
panel[i]=new JPanel();
add(panel[i]);
}
panel[0].setLayout(new GridLayout(1,1,3,3));
panel[1].setLayout(new GridLayout(1,3,3,3));
panel[2].setLayout(new GridLayout(5,1,3,3));
panel[3].setLayout(new GridLayout(4,5,3,3));
resultText.setHorizontalAlignment(JTextField.RIGHT);
resultText.setAlignmentX(50);
resultText.setEditable(true);
resultText.setFont(new Font("宋體",Font.PLAIN,19));//設置字體
resultText.setBackground(Color.white);
panel[0].add(resultText);
for (int i = 0; i < KEYS.length; i++) {
keys[i] = new JButton(KEYS[i]);
panel[3].add(keys[i]);
if (i%5-3==0){ keys[i].setForeground(Color.red); }
else{keys[i].setForeground(Color.black);}
keys[i].setVisible(true);
keys[i].setFont(new Font(null,Font.PLAIN,17));//設置字體
keys[i].addActionListener(this);
keys[i].setHorizontalAlignment(keys[i].CENTER);
keys[i].setBackground(new Color(255,236,233));
}
keys[4].setFont(new Font(null,Font.PLAIN,13));//設置字體
keys[19].setForeground(Color.red);
for (int i = 0; i < COMMAND.length; i++) {
commands[i] = new JButton(COMMAND[i]);
panel[1].add(commands[i]);
commands[i].setForeground(Color.red);
commands[i].addActionListener(this);
}
commands[0].setFont(new Font(null,Font.PLAIN,12));//設置字體
for (int i = 0; i < M.length; i++) {
m[i] = new JButton(M[i]);
panel[2].add(m[i]);
m[i].setForeground(Color.red);
m[i].addActionListener(this);
}
panel[0].setBounds(2, 0, 370, 30);
panel[1].setBounds(74, 30, 298, 29);
panel[2].setBounds(2,30, 70, 150);
panel[3].setBounds(74,60, 300, 120);
validate();
}
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if (label.equals(COMMAND[0])){ //用戶按了"Backspace"鍵
handleBackspace();
} else if (label.equals(COMMAND[1])) { //用戶按了"CE"鍵
resultText.setText("0");
} else if (label.equals(COMMAND[2])){ //用戶按了"C"鍵
handleC();
} else if (label.equals(M[4])){ //用戶按了"M+"鍵
mr=mr+Double.valueOf(resultText.getText()).doubleValue();
if (mr==0.0){m[0].setText("");}
else {m[0].setText("M");}
} else if (label.equals(M[3])){ //用戶按了"MS"鍵
mr=Double.valueOf(resultText.getText()).doubleValue();
if (mr==0.0){m[0].setText("");}
} else if (label.equals(M[2])){ //用戶按了"MR"鍵
resultText.setText(""+mr);
} else if (label.equals(M[1])){ //用戶按了"MC"鍵
mr=0.0;
m[0].setText("");
} else if (label.equals("sqrt")) { //平方根運算
resultNum = Math.sqrt(Double.valueOf(resultText.getText()).doubleValue());
resultText.setText(String.valueOf(resultNum));
} else if (label.equals("%")){ //百分號運算,除以100
resultNum = Double.valueOf(resultText.getText()).doubleValue() / 100;
resultText.setText(String.valueOf(resultNum));
} else if (label.equals("+/-")){ //正數負數運算
resultNum = Double.valueOf(resultText.getText()).doubleValue() * (-1);
resultText.setText(String.valueOf(resultNum));
} else if (label.equals("1/x")) { //倒數運算
resultNum=Double.valueOf(resultText.getText()).doubleValue();
if (resultNum == 0.0){ //操作不合法
operateValidFlag = false;
resultText.setText("零沒有倒數");
} else {
resultNum = 1 / resultNum;
}
resultText.setText(String.valueOf(resultNum));
} else if ("0123456789.".indexOf(label) >= 0) { //用戶按了數字鍵或者小數點鍵
handleNumber(label);
} else { //用戶按了運算符鍵
handleOperator(label);
}
}
private void handleBackspace() { // 處理Backspace鍵被按下的事件
String text = resultText.getText();
int i = text.length();
if (i > 0) { //退格,將文本最後一個字元去掉
text = text.substring(0, i - 1);
if (text.length() == 0) { //如果文本沒有了內容,則初始化計算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
} else { //顯示新的文本
resultText.setText(text);
}
}
}
private void handleNumber(String key) { // 處理數字鍵被按下的事件
if (firstDigit) { //輸入的第一個數字
resultText.setText(key);
} else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0)){
//輸入的是小數點,並且之前沒有小數點,則將小數點附在結果文本框的後面
resultText.setText(resultText.getText() + ".");
} else if (!key.equals(".")) { //如果輸入的不是小數點,則將數字附在結果文本框的後面
resultText.setText(resultText.getText() + key);
}
firstDigit = false; //以後輸入的肯定不是第一個數字了
}
private void handleC() { //處理C鍵被按下的事件, 初始化計算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
}
private void handleOperator(String key) { //處理運算符鍵被按下的事件
if (operator.equals("÷")) { //除法運算 ,如果當前結果文本框中的值等於0
if (getNumberFromText() == 0.0){ //操作不合法
operateValidFlag = false;
resultText.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("=")){ //賦值運算
resultNum = getNumberFromText();
}
if (operateValidFlag) { //雙精度浮點數的運算
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
resultText.setText(String.valueOf(t1));
} else {
resultText.setText(String.valueOf(resultNum));
}
}
operator = key; //運算符等於用戶按的按鈕
firstDigit = true;
operateValidFlag = true;
}
private double getNumberFromText() { // 從結果文本框中獲取數字
double result = 0;
try {
result = Double.valueOf(resultText.getText()).doubleValue();
}
catch (NumberFormatException e){ }
return result;
}
public static void main(String args[]) {
new 計算器();
}
}
㈦ java課程設計---計算器 要求如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.LinkedList;
import java.io.*;
public class CalculatorWindow extends JFrame implements ActionListener{
NumberButton numberButton[];
OperationButton operationButton[];
JButton 小數點操作,正負號操作,退格操作,等號操作,清零操作,sin;
JTextField resultShow; //顯示計算結果
JTextField showComputerProcess; //顯示當前計算過程
JTextArea saveComputerProcess; //顯示計算步驟
JButton saveButton,Button,clearButton;
LinkedList<String> list; //鏈表用來存放第一個運算數、運算符號和第二個運算數
HandleDigit handleDigit; //負責處理ActionEvent事件
HandleOperation handleOperation ;
HandleBack handleBack;
HandleClear handleClear;
HandleEquality handleEquality;
HandleDot handleDot;
HandlePOrN handlePOrN;
HandleSin handleSin;
public CalculatorWindow(){
setTitle("計算器");
JPanel panelLeft,panelRight;
list=new LinkedList<String>();
resultShow=new JTextField(10);
resultShow.setHorizontalAlignment(JTextField.RIGHT);
resultShow.setForeground(Color.blue);
resultShow.setFont(new Font("TimesRoman",Font.BOLD,16));
resultShow.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
resultShow.setEditable(false);
resultShow.setBackground(Color.white);
showComputerProcess=new JTextField();
showComputerProcess.setHorizontalAlignment(JTextField.CENTER);
showComputerProcess.setFont(new Font("Arial",Font.BOLD,16));
showComputerProcess.setBackground(Color.cyan);
showComputerProcess.setEditable(false);
saveComputerProcess=new JTextArea();
saveComputerProcess.setEditable(false);
saveComputerProcess.setFont(new Font("宋體",Font.PLAIN,16));
numberButton=new NumberButton[10];
handleDigit=new HandleDigit(list,resultShow,showComputerProcess);
for(int i=0;i<=9;i++){
numberButton[i]=new NumberButton(i);
numberButton[i].setFont(new Font("Arial",Font.BOLD,20));
numberButton[i].addActionListener(handleDigit);
}
operationButton=new OperationButton[4];
handleOperation=new HandleOperation(list,resultShow,
showComputerProcess,saveComputerProcess);
String 運算符號[]={"+","-","*","/"};
for(int i=0;i<4;i++){
operationButton[i]=new OperationButton(運算符號[i]);
operationButton[i].setFont(new Font("Arial",Font.BOLD,20));
operationButton[i].addActionListener(handleOperation);
}
小數點操作=new JButton(".");
handleDot=new HandleDot(list,resultShow,showComputerProcess);
小數點操作.addActionListener(handleDot);
正負號操作=new JButton("+/-");
handlePOrN=new HandlePOrN(list,resultShow,showComputerProcess);
正負號操作.addActionListener(handlePOrN);
等號操作=new JButton("=");
handleEquality=new HandleEquality(list,resultShow,
showComputerProcess,saveComputerProcess);
等號操作.addActionListener(handleEquality);
sin=new JButton("sin");
handleSin=new HandleSin(list,resultShow,
showComputerProcess,saveComputerProcess);
sin.addActionListener(handleSin);
退格操作=new JButton("退格");
handleBack=new HandleBack(list,resultShow,showComputerProcess);
退格操作.addActionListener(handleBack);
清零操作=new JButton("C");
handleClear=new HandleClear(list,resultShow,showComputerProcess);
清零操作.addActionListener(handleClear);
清零操作.setForeground(Color.red);
退格操作.setForeground(Color.red);
等號操作.setForeground(Color.red);
sin.setForeground(Color.blue);
正負號操作.setForeground(Color.blue);
小數點操作.setForeground(Color.blue);
panelLeft=new JPanel();
panelRight=new JPanel();
panelLeft.setLayout(new BorderLayout());
JPanel centerInLeft=new JPanel();
panelLeft.add(resultShow,BorderLayout.NORTH);
panelLeft.add(centerInLeft,BorderLayout.CENTER);
centerInLeft.setLayout(new GridLayout(4,5));
centerInLeft.add(numberButton[1]);
centerInLeft.add(numberButton[2]);
centerInLeft.add(numberButton[3]);
centerInLeft.add(operationButton[0]);
centerInLeft.add(清零操作);
centerInLeft.add(numberButton[4]);
centerInLeft.add(numberButton[5]);
centerInLeft.add(numberButton[6]);
centerInLeft.add(operationButton[1]);
centerInLeft.add(退格操作);
centerInLeft.add(numberButton[7]);
centerInLeft.add(numberButton[8]);
centerInLeft.add(numberButton[9]);
centerInLeft.add(operationButton[2]);
centerInLeft.add(sin);
centerInLeft.add(numberButton[0]);
centerInLeft.add(正負號操作);
centerInLeft.add(小數點操作);
centerInLeft.add(operationButton[3]);
centerInLeft.add(等號操作);
panelRight.setLayout(new BorderLayout());
panelRight.add(showComputerProcess,BorderLayout.NORTH);
saveButton=new JButton("保存");
Button=new JButton("復制");
clearButton=new JButton("清除");
saveButton.setToolTipText("保存計算過程到文件");
Button.setToolTipText("復制選中的計算過程");
clearButton.setToolTipText("清除計算過程");
saveButton.addActionListener(this);
Button.addActionListener(this);
clearButton.addActionListener(this);
panelRight.add(new JScrollPane(saveComputerProcess),BorderLayout.CENTER);
JPanel southInPanelRight=new JPanel();
southInPanelRight.add(saveButton);
southInPanelRight.add(Button);
southInPanelRight.add(clearButton);
panelRight.add(southInPanelRight,BorderLayout.SOUTH);
JSplitPane split=new JSplitPane
(JSplitPane.HORIZONTAL_SPLIT,panelLeft,panelRight);
add(split,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBounds(100,50,528,258);
validate();
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==Button)
saveComputerProcess.();
if(e.getSource()==clearButton)
saveComputerProcess.setText(null);
if(e.getSource()==saveButton){
JFileChooser chooser=new JFileChooser();
int state=chooser.showSaveDialog(null);
File file=chooser.getSelectedFile();
if(file!=null&&state==JFileChooser.APPROVE_OPTION){
try{ String content=saveComputerProcess.getText();
StringReader read=new StringReader(content);
BufferedReader in= new BufferedReader(read);
FileWriter outOne=new FileWriter(file);
BufferedWriter out= new BufferedWriter(outOne);
String str=null;
while((str=in.readLine())!=null){
out.write(str);
out.newLine();
}
in.close();
out.close();
}
catch(IOException e1){}
}
}
}
public static void main(String args[]){
new CalculatorWindow();
}
}
㈧ Java計算器實驗報告(含代碼),急!!!!
給你一個吧。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* 一個計算器,與Windows附件自帶計算器的標准版功能、界面相仿。
* 但還不支持鍵盤操作。
*/
public class Calculator extends JFrame implements ActionListener {
/** 計算器上的鍵的顯示名字 */
private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6",
"*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
/** 計算器上的功能鍵的顯示名字 */
private final String[] COMMAND = { "Backspace", "CE", "C" };
/** 計算器左邊的M的顯示名字 */
private final String[] M = { " ", "MC", "MR", "MS", "M+" };
/** 計算器上鍵的按鈕 */
private JButton keys[] = new JButton[KEYS.length];
/** 計算器上的功能鍵的按鈕 */
private JButton commands[] = new JButton[COMMAND.length];
/** 計算器左邊的M的按鈕 */
private JButton m[] = new JButton[M.length];
/** 計算結果文本框 */
private JTextField resultText = new JTextField("0");
// 標志用戶按的是否是整個表達式的第一個數字,或者是運算符後的第一個數字
private boolean firstDigit = true;
// 計算的中間結果。
private double resultNum = 0.0;
// 當前運算的運算符
private String operator = "=";
// 操作是否合法
private boolean operateValidFlag = true;
/**
* 構造函數
*/
public Calculator(){
super();
//初始化計算器
init();
//設置計算器的背景顏色
this.setBackground(Color.LIGHT_GRAY);
this.setTitle("計算器");
//在屏幕(500, 300)坐標處顯示計算器
this.setLocation(500, 300);
//不許修改計算器的大小
this.setResizable(false);
//使計算器中各組件大小合適
this.pack();
}
/**
* 初始化計算器
*/
private void init() {
// 文本框中的內容採用右對齊方式
resultText.setHorizontalAlignment(JTextField.RIGHT);
// 不允許修改結果文本框
resultText.setEditable(false);
// 設置文本框背景顏色為白色
resultText.setBackground(Color.white);
//初始化計算器上鍵的按鈕,將鍵放在一個畫板內
JPanel calckeysPanel = new JPanel();
//用網格布局器,4行,5列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
calckeysPanel.setLayout(new GridLayout(4, 5, 3, 3));
for (int i = 0; i < KEYS.length; i++) {
keys[i] = new JButton(KEYS[i]);
calckeysPanel.add(keys[i]);
keys[i].setForeground(Color.blue);
}
//運算符鍵用紅色標示,其他鍵用藍色表示
keys[3].setForeground(Color.red);
keys[8].setForeground(Color.red);
keys[13].setForeground(Color.red);
keys[18].setForeground(Color.red);
keys[19].setForeground(Color.red);
//初始化功能鍵,都用紅色標示。將功能鍵放在一個畫板內
JPanel commandsPanel = new JPanel();
//用網格布局器,1行,3列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
commandsPanel.setLayout(new GridLayout(1, 3, 3, 3));
for (int i = 0; i < COMMAND.length; i++) {
commands[i] = new JButton(COMMAND[i]);
commandsPanel.add(commands[i]);
commands[i].setForeground(Color.red);
}
//初始化M鍵,用紅色標示,將M鍵放在一個畫板內
JPanel calmsPanel = new JPanel();
//用網格布局管理器,5行,1列的網格,網格之間的水平方向間隔為3個象素,垂直方向間隔為3個象素
calmsPanel.setLayout(new GridLayout(5, 1, 3, 3));
for (int i = 0; i < M.length; i++) {
m[i] = new JButton(M[i]);
calmsPanel.add(m[i]);
m[i].setForeground(Color.red);
}
//下面進行計算器的整體布局,將calckeys和command畫板放在計算器的中部,
//將文本框放在北部,將calms畫板放在計算器的西部。
//新建一個大的畫板,將上面建立的command和calckeys畫板放在該畫板內
JPanel panel1 = new JPanel();
//畫板採用邊界布局管理器,畫板里組件之間的水平和垂直方向上間隔都為3象素
panel1.setLayout(new BorderLayout(3, 3));
panel1.add("North", commandsPanel);
panel1.add("West", calckeysPanel);
//建立一個畫板放文本框
JPanel top = new JPanel();
top.setLayout(new BorderLayout());
top.add("Center", resultText);
//整體布局
getContentPane().setLayout(new BorderLayout(3, 5));
getContentPane().add("North", top);
getContentPane().add("Center", panel1);
getContentPane().add("West", calmsPanel);
//為各按鈕添加事件偵聽器
//都使用同一個事件偵聽器,即本對象。本類的聲明中有implements ActionListener
for (int i = 0; i < KEYS.length; i++) {
keys[i].addActionListener(this);
}
for (int i = 0; i < COMMAND.length; i++) {
commands[i].addActionListener(this);
}
for (int i = 0; i < M.length; i++) {
m[i].addActionListener(this);
}
}
/**
* 處理事件
*/
public void actionPerformed(ActionEvent e) {
//獲取事件源的標簽
String label = e.getActionCommand();
if (label.equals(COMMAND[0])){
//用戶按了"Backspace"鍵
handleBackspace();
} else if (label.equals(COMMAND[1])) {
//用戶按了"CE"鍵
resultText.setText("0");
} else if (label.equals(COMMAND[2])){
//用戶按了"C"鍵
handleC();
} else if ("0123456789.".indexOf(label) >= 0) {
//用戶按了數字鍵或者小數點鍵
handleNumber(label);
// handlezero(zero);
} else {
//用戶按了運算符鍵
handleOperator(label);
}
}
/**
* 處理Backspace鍵被按下的事件
*/
private void handleBackspace() {
String text = resultText.getText();
int i = text.length();
if (i > 0) {
//退格,將文本最後一個字元去掉
text = text.substring(0, i - 1);
if (text.length() == 0) {
//如果文本沒有了內容,則初始化計算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
} else {
//顯示新的文本
resultText.setText(text);
}
}
}
/**
* 處理數字鍵被按下的事件
* @param key
*/
private void handleNumber(String key) {
if (firstDigit) {
//輸入的第一個數字
resultText.setText(key);
} else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0)){
//輸入的是小數點,並且之前沒有小數點,則將小數點附在結果文本框的後面
resultText.setText(resultText.getText() + ".");
} else if (!key.equals(".")) {
//如果輸入的不是小數點,則將數字附在結果文本框的後面
resultText.setText(resultText.getText() + key);
}
//以後輸入的肯定不是第一個數字了
firstDigit = false;
}
/**
* 處理C鍵被按下的事件
*/
private void handleC() {
//初始化計算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
}
/**
* 處理運算符鍵被按下的事件
* @param key
*/
private void handleOperator(String key) {
if (operator.equals("/")) {
//除法運算
//如果當前結果文本框中的值等於0
if (getNumberFromText() == 0.0){
//操作不合法
operateValidFlag = false;
resultText.setText("除數不能為零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("1/x")) {
//倒數運算
if (resultNum == 0.0){
//操作不合法
operateValidFlag = false;
resultText.setText("零沒有倒數");
} else {
resultNum = 1 / resultNum;
}
} else if (operator.equals("+")){
//加法運算
resultNum += getNumberFromText();
} else if (operator.equals("-")){
//減法運算
resultNum -= getNumberFromText();
} else if (operator.equals("*")){
//乘法運算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
//平方根運算
resultNum = Math.sqrt(resultNum);
} else if (operator.equals("%")){
//百分號運算,除以100
resultNum = resultNum / 100;
} else if (operator.equals("+/-")){
//正數負數運算
resultNum = resultNum * (-1);
} else if (operator.equals("=")){
//賦值運算
resultNum = getNumberFromText();
}
if (operateValidFlag) {
//雙精度浮點數的運算
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
resultText.setText(String.valueOf(t1));
} else {
resultText.setText(String.valueOf(resultNum));
}
}
//運算符等於用戶按的按鈕
operator = key;
firstDigit = true;
operateValidFlag = true;
}
/**
* 從結果文本框中獲取數字
* @return
*/
private double getNumberFromText() {
double result = 0;
try {
result = Double.valueOf(resultText.getText()).doubleValue();
} catch (NumberFormatException e){
}
return result;
}
public static void main(String args[]) {
Calculator calculator1 = new Calculator();
calculator1.setVisible(true);
calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
㈨ 怎麼寫計算器設計報告
目 錄
1 前言 2
2 需求分析 2
2.1要求 2
2.2任務 2
2.3運行環境 2
2.4開發工具 2
3 概要設計 2
3.1系統流程圖 3
3.2查詢函數流程圖 4
4 詳細設計 6
4.1分析和設計 6
4.2具體代碼實現 6
4.3程序運行結果 14
5 課程設計總結 14
參考文獻 15
致 謝 15
1 前言
編寫一個程序來實現算術計算器.通過結構體數組和共用體數組來存放輸入的每一數字或運算符號的記錄(包括1、2、3等數字,+、--、*、等運算符號),然後將其信息存入文件中.輸入一個算術計算式,就在屏幕上顯示結果.
2 需求分析
2.1要求
(1)用C語言實現程序設計;
(2)利用結構體、共用體進行相關信息處理;
(3)畫出查詢模塊的流程圖;
(4)系統的各個功能模塊要求用函數的形式實現;
(5)界面友好(良好的人機互交),程序要有注釋.
2.2任務
(1)定義一個結構體類型數組,輸入0~9及+、--、*等符號的信息,將其信息存入文件中;
(2)輸入簡單的加減乘除算術計算式,並在屏幕上顯示計算結果;
(3)畫出部分模塊的流程圖;
(4)編寫代碼;
(5)程序分析與調試.
2.3運行環境
(1)WINDOWS2000/XP系統
(2)TurboC2.0編譯環境
2.4開發工具
C語言
3 概要設計
3.1系統流程圖
如圖3.1所示.
w
圖3.1 系統流程圖
3.2查詢函數流程圖
(1) 邊界畫線函數流程圖
(2)圖標按鈕設置函數流程圖
4 詳細設計
4.1分析和設計
(1)在程序的開頭部分定義了結構體類型,用來存放按鈕信息,使數據能夠從鍵盤上輸入.用輸入函數input()來輸入按鍵放在button[]數組中.再定義結構體棧:struct_stack() 用於數據的輸入和存放.
(2)進而定義了表格窗口函數,窗口畫線函數draw_win() 和邊界線函數draw_border(),定義out_text_win()輸出文本窗口,定義window_xy(32,3); 計算結果窗口.通過這些為形成整個界面提供了大的前提.
(3)接著通過「write_char()」,「active_button()」,「 write_top()」,「out_text_win()」,「get_key()」 ,「window_xy()」等一系列的函數,使得計算器的整個外型呈現了出來.再定義了文本游標函數:text_clo()文本游標函數,通過游標移動選定數字並按空格鍵確定,通過mian()函數來調用各個子函數,最終得到結果.
4.2具體代碼實現
源程序代碼:
#include"dos.h"
#include"conio.h"
#include"string.h"
#include"stdio.h"
#define normbut_bor 0x80
#define presbut_but 0xb8
#define normnum_but 0x8e
#define presnum_but 0xb9
#define spebut_char 0x2c
#define win_color 0xf2
#define win_char 0xfb
struct s_button /*按鍵的結構體*/
{ int sx,sy,ex,ey;
char *head;
int press;
}button[17]; /*圖表按鍵數*/
struct stack /*結構體棧*/
{ char s[20];
int tos,top;
}stack;
char tag;
{
if(stack.tos>0)
stack.s[--stack.tos]='\0';
}
draw_win() /*邊框畫線窗口*/
{
int i;
char far *t;
char *s="This is a simple calculator!"; /*頂端邊框輸出的字元*/
draw_border(30,0,79,24,win_color); /*邊框的位置和顏色*/
i=(79-30-strlen(s))/2+30;
t=vid_mem+i*2;
for(;*s;)
{
*t++=*s++;
*t++=win_color; /*頂端字體顏色*/
}
}
draw_border(int sx,int sy,int ex,int ey,int attrib) /*邊界線函數*/
{
char far *t,far *v;
int i;
t=vid_mem;
for(i=sx+1;i