The examples in this article summarize the common methods used to write calculators in Java. Share to everyone for your reference, specific as follows:
Method One:
Package Wanwa;
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*; public class Calculator extends JFrame {private Container Container; private gridbaglayout layout; private Gridbagconstra
INTs constraints; Private JTextField displayfield;//calculation results display area private String lastcommand;//save +,-, *,/,= command private double result;//save calculation results pri Vate Boolean start;//Determines whether the start of the number is public Calculator () {Super ("Calculator"); container = Getcontentpane (); layout = new Gri
Dbaglayout ();
Container.setlayout (layout);
constraints = new gridbagconstraints ();
Start = true;
result = 0;
Lastcommand = "=";
Displayfield = new JTextField (20);
Displayfield.sethorizontalalignment (Jtextfield.right);
Constraints.gridx = 0;
Constraints.gridy = 0;
Constraints.gridwidth = 4;
Constraints.gridheight = 1;
Constraints.fill = Gridbagconstraints.both;
CONSTRAINTS.WEIGHTX = 100;
constraints.weighty = 100;
Layout.setconstraints (Displayfield, constraints);
Container.add (Displayfield); ActionListener Insert = new InsertactiOn ();
ActionListener command = new Commandaction ();
AddButton ("Backspace", 0, 1, 2, 1, insert);
AddButton ("CE", 2, 1, 1, 1, insert);
AddButton ("C", 3, 1, 1, 1, insert);
AddButton ("7", 0, 2, 1, 1, insert);
AddButton ("8", 1, 2, 1, 1, insert);
AddButton ("9", 2, 2, 1, 1, insert);
AddButton ("/", 3, 2, 1, 1, command);
AddButton ("4", 0, 3, 1, 1, insert);
AddButton ("5", 1, 3, 1, 1, insert);
AddButton ("6", 2, 3, 1, 1, insert);
AddButton ("*", 3, 3, 1, 1, command);
AddButton ("1", 0, 4, 1, 1, insert);
AddButton ("2", 1, 4, 1, 1, insert);
AddButton ("3", 2, 4, 1, 1, insert);
AddButton ("-", 3, 4, 1, 1, command);
AddButton ("0", 0, 5, 1, 1, insert);
AddButton ("+ +", 1, 5, 1, 1, insert);//Only Show "-" number, "+" has no practical value AddButton (".", 2, 5, 1, 1, insert);
AddButton ("+", 3, 5, 1, 1, command);
AddButton ("=", 0, 6, 4, 1, command);
This.setresizable (FALSE);
SetSize (180, 200);
SetVisible (TRUE); private void AddButton (String label, int row, int column, int with, int height, ActionListener listener) {JButtonbutton = new JButton (label);
Constraints.gridx = row;
constraints.gridy = column;
Constraints.gridwidth = with;
Constraints.gridheight = height;
Constraints.fill = Gridbagconstraints.both;
Button.addactionlistener (listener);
Layout.setconstraints (button, constraints);
Container.add (button); Private class Insertaction implements ActionListener {public void actionperformed (ActionEvent event) {String input = E
Vent.getactioncommand ();
if (start) {Displayfield.settext ("");
start = false;
if (input.equals ("+ +")) Displayfield.settext (Displayfield.gettext () + "-"); } if (!input.equals ("+ +")) {if (Input.equals ("Backspace")) {String str = displayfield.gettext (); if (Str.length ()
> 0) displayfield.settext (str.substring (0, Str.length ()-1)); else if (input.equals ("CE") | | input.equals ("C")) {Displayfield.settext ("0"); start = true;} else Displayfield.settext
(Displayfield.gettext () + input); }} Private class Commandaction implements ActionListener {public void ActionperFormed (ActionEvent evt) {String command = Evt.getactioncommand ();
if (start) {lastcommand = command;
else {calculate (double.parsedouble (Displayfield.gettext ()));
Lastcommand = command;
Start = true; }} public void calculate (double x) {if (Lastcommand.equals ("+")) result = = X or else if (lastcommand.equals ("-)") result
-= x;
else if (lastcommand.equals ("*")) result *= x;
else if (lastcommand.equals ("/")) result/= x;
else if (lastcommand.equals ("=")) result = x;
Displayfield.settext ("" + result);} public static void Main (string[] args) {Calculator Calculator = new Calculator (), Calculator.setdefaultcloseoperation (JF Rame.
Exit_on_close);
}
}
Method Two:
Import java.awt.*;
Import java.awt.event.*;
public class Mycalculator {PRivate Frame F;
Private TextField tf = new TextField (30);
private long result;
Private Boolean append=false;
Private char operator= ' = ';
Private button[] Btn=new button[15];
Public Mycalculator () {initcomponent ();
private void InitComponent () {f = new Frame ("My Calculator V1.0"); F.setlayout (New BorderLayout ());
The frame uses BorderLayout F.addwindowlistener (new Windowadapter () {public void windowclosing (WindowEvent evt) {
System.exit (0);
}
});
Panel centerpanel = new Panel (); Centerpanel.setlayout (New GridLayout (5, 3));
The panel uses GridLayout numberlistener nl=new numberlistener ();
Operatorlistener ol=new Operatorlistener ();
Btn[10]=new button ("+");
Btn[11]=new button ("-");
Btn[12]=new button ("*");
Btn[13]=new button ("/");
Btn[14]=new button ("=");
for (int i=0;i<=9;i++) {btn[i]=new Button (string.valueof (i));
Centerpanel.add (Btn[i]); Btn[i].addActionListener (NL);
if (i%2==1) {Centerpanel.add (btn[(i+19)/2]);
btn[(i+19)/2].addactionlistener (OL);
} f.add (Centerpanel, Borderlayout.center);
Panel northpanel = new Panel ();
Tf.seteditable (FALSE);
Northpanel.add (TF);
F.add (Northpanel, Borderlayout.north);
public void Go () {f.pack ();
F.setvisible (TRUE);
public static void Main (string[] args) {new Mycalculator (). Go ();
/** * Adopts the member inner class way, implements the listener interface, facilitates the access to the class internal members within the main class.
* This class is responsible for Digital button action event monitoring and processing * * Class Numberlistener implements actionlistener{public void actionperformed (ActionEvent e) {
if (!append) {Tf.settext ("");
Append=true;
} String S=tf.gettext ();
S+=e.getactioncommand ();
Tf.settext (s);
if (!btn[10].isenabled ()) {for (int i=10;i<=14;i++) btn[i].setenabled (true); }}/** * member inner class, responsible for event handling of operator Button/class Operatorlistener implements actionlistener{public void actionperformed (A
Ctionevent e) {if (!append) return; for (int i=10;i<=14;i++) btn[I].setenabled (FALSE);
String S=tf.gettext (); Long Num=long.parselong (s);//get the number of TextField append=false;
Set append switch (operator) {case ' + ': result+=num;break;
Case '-': result-=num;break;
Case ' * ': result*=num;break;
Case '/': {if (num==0) result=0;
else Result/=num;
Break
Case ' = ': result=num;break;
} tf.settext (Result) (string.valueof);
Set the value of result to TextField String Op=e.getactioncommand (); Operator=op.charat (0);
Set operator}}}
Method Three:
Package Wanwa;
Import java.util.*;
public class Calc {public static void main (string[] args) {Scanner input = new Scanner (system.in);
System.out.println ("***************** Simple calculator ****************");
System.out.println ("*\t\t\t\t\t*");
SYSTEM.OUT.PRINTLN ("* Use instructions: 1. Addition 2. Subtraction 3. Multiplication 4. Division *");
System.out.println ("*\t\t\t\t\t*");
System.out.println ("*****************************************");
for (int i=0;i<100;i++) {System.out.print (\ n Please select an operation rule:); int num = Input.nextint (); switch (num) {Case 1:
System.out.println ("\n****** one chose the addition ******\n");
System.out.print ("Please enter 1th addends:");
int jiashu1 = Input.nextint ();
System.out.print ("Please enter 2nd addends:");
int jiashu2 = Input.nextint ();
SYSTEM.OUT.PRINTLN ("The result of the operation is:" + jiashu1 + "+" + jiashu1 + "=" + (JIASHU1 + jiashu2));
Break
Case 2:system.out.println ("\n****** you chose subtraction ******\n");
System.out.print ("Please enter by meiosis:");
int jianshu1 = Input.nextint ();
System.out.print ("Please enter meiosis:");
int jianshu2 = Input.nextint (); SYSTEM.OUT.PRINTLN ("The result of the operation is:" + jianshu1 + "-" + jianshu2 + "="+ (JIANSHU1-JIANSHU2));
Break
Case 3:system.out.println ("\n****** you have chosen multiplication ******\n");
System.out.print ("Please enter a 1th factor:");
int chengfa1 = Input.nextint ();
System.out.print ("Please enter a 2nd factor:");
int chengfa2 = Input.nextint ();
SYSTEM.OUT.PRINTLN ("The result of the operation is:" + chengfa1 + "*" + chengfa2 + "=" + (CHENGFA1 * chengfa2));
Break
Case 4:system.out.println ("\n****** you have chosen division ******\n");
System.out.print ("Please enter dividend:");
Double chufa1 = Input.nextint ();
System.out.print ("Please enter divisor:");
Double CHUFA2 = Input.nextint ();
SYSTEM.OUT.PRINTLN ("The result of the operation is:" + chufa1 + "/" + CHUFA2 + "=" + (CHUFA1/CHUFA2) + "+" + (chufa1% chufa2));
Break
Default:System.out.println ("Your choice is wrong, please choose again!");
Break
}
}
}
}
Method Four:
Package Wanwa;
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*; public class Calculator extends JFrame {private Container Container; private gridbaglayout layout; private Gridbagconstra
INTs constraints; Private JTextField displayfield;//calculation results display area private String lastcommand;//save +,-, *,/,= command private double result;//save calculation results pri Vate Boolean start;//Determines whether the start of the number is public Calculator () {Super ("Calculator"); container = Getcontentpane (); layout = new Gri
Dbaglayout ();
Container.setlayout (layout);
constraints = new gridbagconstraints ();
Start = true;
result = 0;
Lastcommand = "=";
Displayfield = new JTextField (20);
Displayfield.sethorizontalalignment (Jtextfield.right);
Constraints.gridx = 0;
Constraints.gridy = 0;
Constraints.gridwidth = 4;
Constraints.gridheight = 1;
Constraints.fill = Gridbagconstraints.both;
CONSTRAINTS.WEIGHTX = 100;
constraints.weighty = 100;
Layout.setconstraints (Displayfield, constraints);
Container.add (Displayfield); ActionListener Insert = new InsertactiOn ();
ActionListener command = new Commandaction ();
AddButton ("Backspace", 0, 1, 2, 1, insert);
AddButton ("CE", 2, 1, 1, 1, insert);
AddButton ("C", 3, 1, 1, 1, insert);
AddButton ("7", 0, 2, 1, 1, insert);
AddButton ("8", 1, 2, 1, 1, insert);
AddButton ("9", 2, 2, 1, 1, insert);
AddButton ("/", 3, 2, 1, 1, command);
AddButton ("4", 0, 3, 1, 1, insert);
AddButton ("5", 1, 3, 1, 1, insert);
AddButton ("6", 2, 3, 1, 1, insert);
AddButton ("*", 3, 3, 1, 1, command);
AddButton ("1", 0, 4, 1, 1, insert);
AddButton ("2", 1, 4, 1, 1, insert);
AddButton ("3", 2, 4, 1, 1, insert);
AddButton ("-", 3, 4, 1, 1, command);
AddButton ("0", 0, 5, 1, 1, insert);
AddButton ("+ +", 1, 5, 1, 1, insert);//Only Show "-" number, "+" has no practical value AddButton (".", 2, 5, 1, 1, insert);
AddButton ("+", 3, 5, 1, 1, command);
AddButton ("=", 0, 6, 4, 1, command);
This.setresizable (FALSE);
SetSize (180, 200);
SetVisible (TRUE); private void AddButton (String label, int row, int column, int with, int height, ActionListener listener) {JButtonbutton = new JButton (label);
Constraints.gridx = row;
constraints.gridy = column;
Constraints.gridwidth = with;
Constraints.gridheight = height;
Constraints.fill = Gridbagconstraints.both;
Button.addactionlistener (listener);
Layout.setconstraints (button, constraints);
Container.add (button); Private class Insertaction implements ActionListener {public void actionperformed (ActionEvent event) {String input = E
Vent.getactioncommand ();
if (start) {Displayfield.settext ("");
start = false;
if (input.equals ("+ +")) Displayfield.settext (Displayfield.gettext () + "-"); } if (!input.equals ("+ +")) {if (Input.equals ("Backspace")) {String str = displayfield.gettext (); if (Str.length ()
> 0) displayfield.settext (str.substring (0, Str.length ()-1)); else if (input.equals ("CE") | | input.equals ("C")) {Displayfield.settext ("0"); start = true;} else Displayfield.settext
(Displayfield.gettext () + input); }} Private class Commandaction implements ActionListener {public void ActionperFormed (ActionEvent evt) {String command = Evt.getactioncommand ();
if (start) {lastcommand = command;
else {calculate (double.parsedouble (Displayfield.gettext ()));
Lastcommand = command;
Start = true; }} public void calculate (double x) {if (Lastcommand.equals ("+")) result = = X or else if (lastcommand.equals ("-)") result
-= x;
else if (lastcommand.equals ("*")) result *= x;
else if (lastcommand.equals ("/")) result/= x;
else if (lastcommand.equals ("=")) result = x;
Displayfield.settext ("" + result);} public static void Main (string[] args) {Calculator Calculator = new Calculator (), Calculator.setdefaultcloseoperation (JF Rame.
Exit_on_close);
}
}
I hope this article will help you with your Java programming.