Java implementation Windows7-standard Calculator

Source: Internet
Author: User

The program can realize the basic arithmetic operation, and can control the precision of the result of operation effectively, and realizes the memory related function.

The functions are as follows:

MC: Clear Storage Data MR: Read stored data is displayed on the screen MS: Store the displayed data overlay in memory m+: Add the stored data to the number displayed on the screen and update the values in the memory m: subtract the number displayed on the screen with stored data and update the value in the memory ←: Delete the mantissa of the input number C:   Clear Calculator data, next time input data start a new operation CE:  clears the current input ±:  positive negative number conversion Yes:  Open square +,-, *,/subtraction, result%: modulo 1/x: Take the countdown

Program Flowchart:



Code implementation:

Class Operatenum {//operand class public double value;//the actual value of the operand public int dotwei;//operand if it is a decimal, the number of digits after the decimal point is logged public String invertedstring;//1/x Strings public string sqrtedstring;//sqrt (x) Strings public Boolean issqrted,isinverted;//does the token √,1/x over, The public boolean clear;//clear is used for subsequent judgment to indicate whether to reset the operand public boolean isfloat;//isfloat to True, indicating that the operand is a decimal public operatenum () {value=0 ;d Otwei=0;sqrtedstring=null;invertedstring=null;issqrted=false;isinverted=false;clear=false;isfloat=false;} public void Reset ()//reset operand {value=0;dotwei=0;sqrtedstring=null;invertedstring=null;issqrted=false;isinverted= False;clear=false;isfloat=false;}}


Class Storagefield {//Store public double storagenum;//store data public boolean storagemode;//whether to start store public Storagefield () {Storagenum=0;storagemode=false;}}


Import Java.awt.*;import Java.awt.event.keyadapter;import Java.awt.event.keyevent;import Java.awt.event.mouseadapter;import Java.awt.event.mouseevent;import Java.math.bigdecimal;import javax.swing.*; Import Javax.swing.border.border;import Javax.swing.border.lineborder;public class Calc extends Jframe{private JTextField display1,display2,display3;private JButton num[],operate[];p rivate String name[]={"MC", "MR", "MS", "m+", " M-"," ← "," CE "," C "," ± "," √ "," 7 "," 8 "," 9 ","/","% "," 4 "," 5 "," 6 "," * "," 1/x "," 1 "," 2 "," 3 ","-"," = "," 0 ",". "," + "};p rivate Operatenum op1=new operatenum (), Op2=new operatenum ();//operand 1, operand 2private storagefield storage=new storagefield ();// The store private string action= "OP1";//Represents the object to be manipulated "OP1" operation the first operand, "OP2" action the second operand private string sign= "";//operator, default is empty private string Screen1,screen2;private boolean Disable=false;public calc () {Super ("Calculator"); This.setlayout (null); This.setsize (228, 324); this.setresizable (false); JPanel jp=new JPanel (null); Jp.setbounds (10,15,getwidth () -24,getheight ()); Jp.setbackground (newColor (217,228,241)); This.getcontentpane (). SetBackground (new color (217,228,241));/** Display **/display1=new JTextField ("");d isplay2=new JTextField ("0");d isplay3=new JTextField ("");d isplay1.setenabled (False);d isplay2.setenabled ( False);d isplay3.setenabled (False);d isplay1.setbounds (0, 0, 204,);d Isplay2.setbounds (20, 20, 184, 34); Display3.setbounds (0,,);d isplay1.sethorizontalalignment (jlabel.right);d isplay2.sethorizontalalignment ( Jlabel.right);d isplay3.sethorizontalalignment (jlabel.center);d Isplay1.setfont (New Font ("Arial", font.plain,12)); Display2.setfont (New Font ("Arial", font.bold,20));d Isplay3.setfont (New Font ("Arial", font.plain,20)); Display1.setdisabledtextcolor (Color.Black);d Isplay2.setdisabledtextcolor (Color.Black); Display3.setdisabledtextcolor (Color.Black);d Isplay1.setborder (New Lineborder (New Color (242,247,252))); Display2.setborder (New Lineborder (242,247,252)));d Isplay3.setborder (new Lineborder (new color (242,247,252) ));d Isplay1.setbackground (New Color (242,247,252));d isplay2.SetBackground (new color (242,247,252));d isplay3.setbackground (new Color (242,247,252)),/** button 35px*29px 28 ***/int i;o Perate=new jbutton[28];/** Top 24 **/for (i=0;i<24;i++) {operate[i]=new JButton (name[i]); Operate[i].setmargin (new Java.awt.Insets (0,0,0,0)); Operate[i].setbounds (i%5* (35+7), 60+i/5* (29+5) +5, Jp.add (Operate[i]);} /***= ***/operate[i]=new JButton (Name[i]); Operate[i].setmargin (new Java.awt.Insets (0,0,0,0)); Operate[i].setbounds (i%5* (35+7), 60+i/5* (29+5) +5, 29*2+5); Jp.add (Operate[i]); i++;/***0 ***/operate[i]=new JButton (Name[i]); Operate[i].setmargin (new Java.awt.Insets (0,0,0,0)); Operate[i].setbounds (i%5* (35+7), 60+i/5* (29+5) +5, 35*2+7), Jp.add (Operate[i]),/** Top 24 **/for (i=i+1;i< name.length;i++) {operate[i]=new JButton (name[i]); Operate[i].setmargin (new Java.awt.Insets (0,0,0,0)); Operate[i]. SetBounds (i+1)%5* (35+7), 60+i/5* (29+5) +5, Jp.add (Operate[i]);} /** * Register mouse Listener with button, keyboard listener and background */mouseadapter ml=new mouseadapter (); Keyadapter kl=new Keyadapter (); for (i=0;i<name.length;i++) {operate[i].addmouselistener (ml), operate[i].addkeylistener (KL); Operate[i].setbackground (new Color (233,240,247)); Operate[i].setforeground (new Color (30,57,91));} Jp.add (display1); Jp.add (display2); Jp.add (DISPLAY3); Jp.addkeylistener (KL); This.add (JP); this.setvisible (true);} Class Mouseadapter extends Mouseadapter{public void mouseclicked (MouseEvent e) {JButton operate= (JButton) E.getsource () if (Disable)//Disable button, click C Recovery Calculator {if (operate.gettext () = = "C") {clear ();D Isable=false;} Elsereturn;} Switch (Operate.gettext ()) {case "MC": MC (); Break;case "Mr": Mr (); Break;case "MS": MS (); Break;case "m+": MAdd (); Case "M": Mcut (); break;case "←": cutend () break;case "CE": Cutnum (); Break;case "C": Clear (); Break;case "±": Revolt (); Break;case "√": sqrt () break;case "7": Case "8": Case "9": Case "4": Case "5": Case "6": Case "3": Case "2": Case "1": Case "0": Rea D (Integer.parseint (Operate.gettext ())) break;//converts the text on the key to the INT case "/":d ivide (); Break;case "%": Mo (); break;case "*" : Mul (); Break;case "1/x": Inverted (); Break;case "-": Cut (); Break;case "+": Add (); Break;case "=": sum (); Break;case ".":d ot (); break;} public void mouseentered (MouseEvent e) {((JButton) E.getsource ()). SetBackground (New Color (255,211,113));} public void mouseexited (MouseEvent e) {((JButton) E.getsource ()). SetBackground (New Color (233,240,247));}} /* * MC cancels the store, emptying the store data */public void MC () {storage.storagenum=0;storage.storagemode=false;display3.settext (null);} /* * Mr Read memory stored data */public void Mr () {op1.value=storage.storagenum;screen2= "" +op1.value;if (Op1.value==math.floor ( Op1.value)) screen2= "" + (int) op1.value;display2.settext (screen2); op1.clear=true;} /* * Ms saves data to memory */public void MS () {Storage.storagenum=op1.value;display3.settext ("M");//The lower left corner of the screen displays the M flag}/* * m+ The number that has been stored plus the current calculation results and will be stored */public void MAdd () {storage.storagenum=storage.storagenum+op1.value;} /* * m already stored minus the current calculation and depositing the difference to memory */public void Mcut () {storage.storagenum=storage.storagenum-op1.value;} /* *← the number of inputs minus the mantissa * */public void Cutend () {if (action== "OP1" &&op1.value!=0)//means operation on OP1 {if (op1.isfloat==false)//If OP1 is an integer {op1.value= (int) op1.value/10;screen2= "" + (int) Op1.value;}   else{//if OP1 is a decimal BigDecimal bd=new BigDecimal (op1.value); Op1.value=bd.setscale (--op1.dotwei,bigdecimal.round_down). Doublevalue () screen2= "" +op1.value;if (op1.dotWei==0) After the decimal digits are removed, the modified integer, updated isfloat tag op1.isfloat=false;}} else if (action== "OP2" &&op2.value!=0)//means operation on OP2 {if (op2.isfloat==false)//If OP2 bit integer {op2.value= (int) Op2.value/10;screen2= "" + (int) Op2.value;}   else{//if OP2 is a decimal BigDecimal bd=new BigDecimal (op2.value); Op2.value=bd.setscale (--op2.dotwei,bigdecimal.round_down). Doublevalue () screen2= "" +op2.value;if (op2.dotWei==0) After the decimal digits are removed, the modified integer, updated isfloat tag op2.isfloat=false;}} Display2.settext (SCREEN2);//output modified operand}/* * CE empties current operand operand */public void cutnum () {if (action== "OP1") op1.reset (); else if ( action== "OP2") Op2.reset ();d Isplay2.settext ("0");//Initialize display 2}/* * C zero Reset calculator */public void Clear () {op1.reset (); op2.reset ();//Initialize data member action= "OP1"; sign= "";//Initialize display Display1.settext ("");d Isplay2.settext ("0");} /* *± positive sign */public voidRevolt () {if (action== "Op1") {op1.value=-op1.value;screen2= "" +op1.value;} else if (action== "Op2") {op2.value=-op2.value;screen2= "" +op2.value;} Display2.settext (SCREEN2);} /* *√ root */public void sqrt () {Double x;//temporary variable if (action== "Op1") {op1.sqrtedstring= "sqrt (" +op1.value+ "); op1.value= MATH.SQRT (op1.value); op1.issqrted=true;x=op1.value;} else{op2.sqrtedstring= "sqrt (" +op2.value+ ")"; op2.value=math.sqrt (op2.value); op2.issqrted=true;x=op2.value;} Screen2=x+ "", if (X==math.floor (x))//If x is an integer {screen2= (int) x+ "",//Then the floating-point x is converted to int and converted to string}display2.settext (SCREEN2);} /* * Press the number key */public void read (int value) {Display2.setfont (new font ("Arial", font.bold,20));//default font size display2.settext (NULL) ;//Clear screen if (op1.clear==true) Op1.reset (), if (op2.clear==true) Op2.reset (), if (action== "OP1")//indicates the output data to Op1{if (op1.isfloat ==true)//If OP1 is floating point {int i=1;double num=value;++op1.dotwei;while (i<=op1.dotwei) {num*=0.1;i++;} op1.value=op1.value+num;//adds the new decimal point to the operand OP1//Because the double-precision floating-point number has a high precision, and we simply take its op1.dotwei to save the op1.value=double.parsedouble ( String.Format ("%." +op1.dotwei+ "F", Op1.value));//Because the precision of the double-precision floating-point number is higher, and we simply take its op1.dotwei display on the screen Display2.settext (String.Format ("%.") +op1.dotwei+ "F", Op1.value));} Else//op1 for integer {op1.value=op1.value*10+value;//adds new integer digits to OP1 display2.settext ((int) op1.value+ "");//Screen output OP1 value}}else if (action== "OP2")//indicates the output data to Op2{if (op2.isfloat==true)//If OP2 is a floating-point number {int i=1;double num=value;++op2.dotwei;while (i<= Op2.dotwei) {num*=0.1;i++;} op2.value=op2.value+num;//adds the new decimal point to the operand OP2//Because the double-precision floating-point number has a high precision, and we simply take its op2.dotwei to save the op2.value=double.parsedouble ( String.Format ("%." +op2.dotwei+ "F", Op2.value));//Because the precision of the double-precision floating-point number is higher, and we simply take its op2.dotwei display on the screen Display2.settext (String.Format ("%.") +op2.dotwei+ "F", Op2.value));} ELSE//OP2 is an integer {op2.value=op2.value*10+value;display2.settext (int) op2.value+ "");}} public void Divide () {run ("/");} public void Mo () {run ("%");} public void Mul () {Run ("*");} /* * 1/x */public void inverted () {double num; String Str;if (action== "OP1") {op1.invertedstring= "1/" +op1.value;//1/x form string op1.value=1/op1.value;op1.isinverted= True;num=op1.value;} Else{op2.invertedstring= "1/" +op2.value;//1/x form string Op2.value=1/op2.value;op1.isinverted=true;num=op2.value;} str=num+ "", if (Str.length () >=16)//Calculator screen can display the maximum length of the data {Display2.setfont (new Font ("Arial", font.bold,14));// Reduce font output display2.settext (str.substring (0, 16));} Elsedisplay2.settext (str);} public void Cut () {run ("-");} public void Add () {run ("+");} public void sum () {Display2.setfont (New Font ("Arial", font.bold,20)); int D1=op1.dotwei,d2=op2.dotwei,i;switch (sign) {// After operation the result is saved to OP1 case "+": Op1.value=op1.value+op2.value;break;case "-": Op1.value=op1.value-op2.value;break;case "*": O P1.value=op1.value*op2.value;break;case "/": Op1.value=op1.value/op2.value;break;case "%": op1.value=op1.value%o P2.value;break;} if (op2.value==0&&sign== "/")//Divisor is 0{disable=true;display2.settext (op1.value+ "");d isplay1.settext (null); Action= "OP1"; return;} if (Op1.value==math.floor (Op1.value))//The result is an integer {display2.settext (int) op1.value+ ""); Op1.dotwei=0;op1.isfloat=false ;} else{//result is a decimal string str=op1.value+ "";//accurate control of the precision of the arithmetic results, plus, minus, modulo operations, the effective number after the decimal point is max (D1,D2) bit if (sIgn.equals ("+") | | Sign.equals ("-") | | Sign.equals ("%")) {i=d1>d2?d1:d2;str=op1.value+ ""; str=str.substring (0, Str.indexof (".") +I+1);///Take I-bit output}//accurately control the precision of arithmetic results, multiplication, the number of valid digits after the decimal point is d1+d2 bit else if (sign.equals ("*")) {i=d1+d2; BigDecimal bd=new BigDecimal (op1.value); Op1.value=bd.setscale (I,bigdecimal.round_down). Doublevalue () str=op1.value+ "";//Update the modified str}//result beyond the maximum length of the displayed data if ( Str.length () >=16) {Display2.setfont (New Font ("Arial", font.bold,14)); str=str.substring (0, 16);} Display2.settext (str); Op1.dotwei=str.length ()-str.indexof (".") -1;//Update op1w value}display1.settext (null) action= "OP1" op1.clear=true;//start a new expression operation OP1 First reset op2.clear=true;// When you start a new expression operation, OP2 resets sign= "";} public void dot () {if (action== "OP1") Op1.isfloat=true;elseop2.isfloat=true;display2.settext (Display2.gettext () + ".");} public void run (String sign) {Display2.setfont (New Font ("Arial", font.bold,20)); action= "OP2"; int d1=op1.dotwei,d2= Op2.dotwei,i;if (!sign.equals (""))//detects if the result of the first operation {switch (sign) {////operation for the expression is saved to OP1 case "+": op1.value=op1.value+ Op2.value;break;case "-": Op1.value=op1.value-op2.value;break;case "*": Op1.value=op1.value*op2.value;break;case "/": op1.value=op1.value/ Op2.value;break;case "%": op1.value=op1.value%op2.value;break;}} String Temp=isspecilehandle (); if (temp==null) temp=display2.gettext ();//Save the data in the Display2 text box first if (op2.value==0& &sign== "/")//Divisor is 0{disable=true;display2.settext (op1.value+ "");d Isplay1.settext (Display1.gettext () + Op1.value);} if (Op1.value==math.floor (Op1.value))//The result is an integer {display2.settext (int) op1.value+ ""); Op1.dotwei=0;op1.isfloat=false ;} Else{string str=op1.value+ "";//accurate control of the accuracy of arithmetic results, addition, subtraction, modulo operation, the effective number after the decimal point is max (D1,D2) bit if (sign.equals ("+") | | Sign.equals ("-") | | Sign.equals ("%")) {i=d1>d2?d1:d2; BigDecimal bd=new BigDecimal (op1.value); Op1.value=bd.setscale (I,bigdecimal.round_down). Doublevalue () str=op1.value+ "";//Update the modified str}//to accurately control the accuracy of arithmetic results, multiplication , the number of valid digits after the decimal point is d1+d2 bit else if (sign.equals ("*")) {i=d1+d2; BigDecimal bd=new BigDecimal (op1.value); Op1.value=bd.setscale (I,bigdecimal.round_down). Doublevalue () str=op1.value+ "";//update modified str}//resultsThe maximum length of the displayed data is exceeded if (str.length () >=16) {Display2.setfont (New Font ("Arial", font.bold,14)); str=str.substring (0, 16);} Display2.settext (str); Op1.dotwei=str.length ()-str.indexof (".") -1;//after each addition, if the value of the result OP1 is a decimal, the value of OP1W is updated}sign=sign;display1.settext (Display1.gettext () +temp+sign); Op2.value=op1.value ;//After operation, the operand OP2 the default value of OP1 op2.clear=true;//the next time you type data, OP2 to reset op1.clear=false;//next time you type data, OP1 do not reset}/* * isspecilehandle () * Whether the operand is sqrt () or 1/x, and if so, returns "sqrt (x)" or "1/x" string */public string Isspecilehandle () {string temp=null;if (op1.issqrted) { Temp=op1.sqrtedstring;op1.issqrted=false;} else if (op2.issqrted) {temp=op2.sqrtedstring;op2.issqrted=false;} if (op1.isinverted) {temp=op1.invertedstring;op1.isinverted=false;} else if (op2.isinverted) {temp=op2.invertedstring;op2.isinverted=false;} return temp;} Class Keyadapter extends Keyadapter{public void keypressed (KeyEvent e) {int keycode=e.getkeycode (); if (keycode>=96 &&keycode<=105) | | (keycode>=48&&keycode<=57)) Number key {if (keycode>=96) Keycode-=48;switch (keycode) {CAsE 48:read (0); break;case 49:read (1); Break;case 50:read (2); Break;case 51:read (3); Break;case 52:read (4); Break;case 53: Read (5); Break;case 54:read (6); Break;case 55:read (7); Break;case 56:read (8); Break;case 57:read (9); break;}} operator keys +-*/= and. and backspace (* = number) Else if (keycode==110| | KEYCODE==46) | | (keycode==111| | keycode==47) | | (keycode==45| | keycode==109) | | keycode==107| | keycode==106| | keycode==61| | keycode==10| | keycode==8) {if (keycode==110| | keycode==46)) dot (), else if (keycode==111| | keycode==47) Run ("/"); else if (keycode==45| | keycode==109) Run ("-"), else if (keycode==107) run ("+"), else if (keycode==106) Run ("*"), else if (keycode==61| | keycode==10)//= number sum (); else if (keycode==8) Cutend ()}}} public static void Main (string[] args) {//TODO auto-generated method Stubcalc app=new calc ();}}

Program




Java implementation Windows7-standard Calculator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.