SlideShare a Scribd company logo
1 of 36
Java CalculatorChapter 6 Sarah McNellis
Entering Variables into the Calculator Application Code mean Displays the code to begin the Calculator application. Lines 17 through 25 declare the private variables.
Entering Variables into theCalculator Application Import Statements import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import java.text.DecimalFormat; import javax.swing.JOptionPane; public class Calculator extends Frame implements ActionListener { 	private Button keys[]; 	private Panel keypad; 	private TextField lcd; 	private double op1; 	private boolean first; 	private boolean foundKey; 	private boolean clearText; 	private int lastOp; 	private DecimalFormat calcPattern; Class Header Private  Variables Declared
Using Menus in the Calculator Application code means  Displays the beginning of the Calculator() constructor method also the code in the slide also shows the code that to set up the menu system. These are some of the meaning of the codes
Using Menus in the Calculator Application Constructor Method header public Calculator() { 	// create an instance of the menu 	MenuBar mnubar = new MenuBar(); 	setMenuBar(mnuBar); 	// construct and populate the File Menu 	Menu mnuFile = new Menu("File", true); 	setMenuBar(mnuBar); 		MenuItem mnuFileExit = new MenuItem("Exit"); 		mnuFile.and(mnuFileExit); Code to create  Menu bar Code to create  File menu
Using Menus in the Calculator Application Continue // construct and populate the Edit menu 	Menu mnuEdit = new Menu("Edit", true); 	mnuBar.and(mnuEdit); 		MenuItem mnuEditClear = new MenuItem("Clear"); 		mnuEdit.and(mnuEditClear); 		mnuEdit.insertSeparator(1); 		MenuItem mnuEditCopy = new MenuItem("Copy"); 		mnuEdit.and(mnuEditCopy); 		MenuItem mnuEditPaste = new MenuItem("Paste"); 		mnuEdit.and(mnuEditPaste); 	// construct and populate the About menu 	Menu mnuAbout = new Menu("About", true); 		mnuBar.and(mnuAbout); 		 MenuItem mnuAboutCalculator = new MenuItem("About Calculator"); 		 mnuAbout.add(mnuAboutCalculator); Code to create Edit menu Code to create About menu
Using Menus in the Calculator Application Continue // add the ActionListener to each menu item mnuFileExit.addActionListener(this); mnuEditClear.addActionListener(this); mnuEditCopy.addActionListener(this); mnuEditPaste.addActionListener(this); mnuAboutCalculator.addActionListener(this); // assign an ActionCommand to each menu item mnuFileExit.setActionCommand("Exit"); mnuEditClear.setActionCommand("Clear"); mnuEditCopy.setActionCommand("Copy"); mnuEditPaste.setActionCommand("Paste"); mnuAboutCalculator.setActionCommand("About"); addActionListener()  Methods for each menu item setActionCommand() methods for each menu item
Initializing the Calculator Variables code means It display the code to set initial values for the Calculator application.
Initializing the Calculator Variables // construct components and initialize beginning values lcd = new TextField(20); 	lcd.setEditable(false); keypad = new Panel(); keys = new Button[16]; first = true; op1 = 0.0; clearText = true; lastOp= 0; calcPattern = new DecimalFormat("########.########"); Code to initialize variables
Creating the Keypad code means Displays the code to construct and label the keypad buttons, as well as the method to establish the GridLayout to organize the buttons.
Creating the Keypad // construct and assign captions to the Buttons for (int i=0; i<=9; i++) 	key[i] = new Button(String.valueOf(i)); keys[10] = new Button("/"); keys[11] = new Button("*"); keys[12] = new Button("-"); keys[13] = new Button("+"); keys[14] = new Button("="); keys[15] = new Button("."); // set Frame and keypad layout to grid layout setLayout(new BorderLayout()); keypad.setLayout(new GridLayout(4,4,10,10)); Code to construct Buttons using array setLayout() methods set BorderLayout for Frame and GridLayout for keypad
Adding components to the interface code means Displays the code to add the 16 buttons to the panel using the four-row, four-column grid. Line comments within the code will help you understand how each loop and add method takes its turn creating buttons in the keypad.
Adding components to the interface for (int i=7; i<=10; i++) // 7, 8, 9, divide      keypad.add(keys[i]); for (int i=4; i<=6; i++) // 4, 5, 6      keypad.add(keys[i]);  keypad.add(keys[11]); // multiply for (int i=1; i<=3; i++) // 1, 2, 3      keypad.add(keys[i]);   keypad.add(keys[12]); // subtract   keypad.add(keys[0]); // 0 key for (int i=15; i>=13; i--)      keypad.add(keys[i]); // decimal point, =, add (+)                      keys Code to add buttons keypad
Continuation of adding components to the Interface code means It displays the code to add the ActionListener to each of the Buttons.
Continue adding componentsto the Interface Code to add Buttons to keypad for (int i=0; i<keys.length; i++) 	keys[i].addActionListener(this); add(lcd, BorderLayout.NORTH); add(keypad, BorderLayout.CENTER); Lcd TextField and  keypad Panel components Added to frame
Coding the addWindowListenerMethod means It displays the code to add a WindowListener for the Frame
Coding the addWindowListenerMethod Creates occurrence Of windowAdapter() class addWindowListener( 	new WindowAdapter() 	        {                         public void windowClosing(WindowEvent e) 		  { 		     System.exit(0); 		  } 	         } 	); }// end of constructor method addWindowListener() method Overrides  windowClosing() method Brace to add method
Searching for the Exitand Clear Commands code means Displays the code used to search to menu items for a click. During program execution, the ActionCommand of any click in the interface, menu, or button will be stored in the variable arg.
Searching for the Exitand Clear Commands ActionPerformed() Method header public void actionPerformed(ActionEvent e) 	{ 		//test for menu item clicks 		String arg =            				e.getActionCommand(); 		if (arg == "Exit") 			System.exit(0); 		if (arg == "Clear") 		{ 			clearText = true; 			first = true; 			op1 = 0.0; 			lcd.setText("") 			lcd.requestFocus(); 		} Tests For Exit command Code to exit program Tests for Clear command Code to clear Number displayed in Lcd TextField and Reset initial values
Searching for the Copy and Paste Commands code means It displays the code executed if the user clicks Copy or Paste on the Edit menu.
Searching for the Copy and Paste Commands Code Tests if Copy  Command clicked if (arg == "Copy") { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection centents = new StringSelection(lcd.getText()); cb.setContents(contents, null); } if (arg == "Paste") { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable content = cb.getContents(this); try { String s = (String)content.getTransferData(DataFlavor.stringFlavor); lcd.setText(calcPattern.format(Double.parseDouble(s))); } catch (Throwable exc) { lcd.setText("") } } Code to copy display To clipboard Test if Paste command clicked Code to paste data  From clipboard
Searching for the About Calculator Command mean in code It display the code to search for the Calculator command.
Searching for the About Calculator Command Code Test if the About Command was clicked if (arg == "About") 		{ 			String message = "Calculator ver. 1.0OpenExhibit SoftwareCopyright 2007All right reserved"; 			JOptionPane.showMessageDialog(null ,message,"About Calculator", JOptionPane.INFORMATION_MESSAGE); 		} Code to display  About Calculator Message box
Searching the Numeric Buttons Code means It displays the code to search the array of buttons to determine which button the user clicked and to add functionality to the numeric buttons and the decimal point in the actionPerformed() method.
Searching the Numeric Buttons Code // test for button clicks 	foundKey = false; // search for the clicked key for (int i=0; i<keys.length && !foundKey; i++) { if(e.getSource() == keys[i]) { foundKey = true; switch(i) 				{ // number and decimal point buttons case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 15: if(clearText) { lcd.setText(""); clearText = false; } lcd.setText(lcd.getText() + keys[i].getLabel()); break; It displays the code To test for button click Of the numeric Buttons or the  Decimal point button
Searching for the First Operator ButtonClick Code means It displays the code to search the array and add functionality to the operator buttons within the actionPerformed() method.
Searching for the First Operator ButtonClick Code // operator buttons case 10: case 11: case 12: case 13: case 14: clearText = true; if (first) // first operand { if(lcd.getText().length()==0) op1 = 0.0; else op1 = Double.parseDouble(lcd.getText()); 	first = false; 	clearText = true; 	lastOp = i; //save last operator } It displays the code to  Handle the first operator Button click in a  calculation
Searching for Subsequent OperatorClicks code means This displays is the code that executes on subsequent operator click
Searching for Subsequent OperatorClicks code else // second operand { switch(lastOp) { case 10: // divide button op1 /= Double.parseDouble(lcd.getText()); break; case 11: // multiply button op1 *= Double.parseDouble(lcd.getText()); break; case 12: // minus button op1 -= Double.parseDouble(lcd.getText()); break; case 13: // plus button op1 += Double.parseDouble(lcd.getText()); break; } // end of switch(lastOp) lcd.setText(calcPattern.format(op1)); clearText = true; The code to handle Subsequent operator Button click in a calculation
Searching for the Equal Button code means When the user specifically clicks the equal button, the lastOp variable is assigned a value of 14, which is the index number of the equal button.
Searching for the Equal Button code The cod to handle a click of  The equal button,  Represented by the subscript 14 in the array. if(i==14) first = true;//equal button else lastOp = i; // save last operator } // end else break; } // end of switch(i) } // end of if } // end of for } // end of actionPerformed
Coding the main() Method for the Calculator class coding means The main() method for the Calculator application constructs an instance of the Calculator class and then sets three attributes.
Coding the main() Method for the Calculator class public static void main(String args[]) { // set frame properties Calculator f = new Calculator(); f.setTitle("Calculator Application"); f.setBounds(200,200,300,300); f.setVisible(true); // set image properties and add to frame Image icon = Toolkit.getDefaultToolkit().getImage("calcImage.gif"); f.setIconImage(icon); } // end of main }// end of class
Print screen of the Calculator
Link to the file Calculator
Work Cited Shelly Cashman Starks Mick: “Java Programming comprehensive Concepts and Techniques” third Edition print 2006

More Related Content

What's hot

Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDrRajeshreeKhande
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
 
Csphtp1 05
Csphtp1 05Csphtp1 05
Csphtp1 05HUST
 
CIS 115 Exceptional Education - snaptutorial.com
CIS 115   Exceptional Education - snaptutorial.comCIS 115   Exceptional Education - snaptutorial.com
CIS 115 Exceptional Education - snaptutorial.comDavisMurphyB33
 
project report in C++ programming and SQL
project report in C++ programming and SQLproject report in C++ programming and SQL
project report in C++ programming and SQLvikram mahendra
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#Giorgio Zoppi
 
OOP program questions with answers
OOP program questions with answersOOP program questions with answers
OOP program questions with answersQuratulain Naqvi
 
Csphtp1 13
Csphtp1 13Csphtp1 13
Csphtp1 13HUST
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Javasuraj pandey
 
CIS 115 Education Specialist / snaptutorial.com
CIS 115  Education Specialist / snaptutorial.comCIS 115  Education Specialist / snaptutorial.com
CIS 115 Education Specialist / snaptutorial.comMcdonaldRyan138
 
02 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_0202 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_02Pooja Gupta
 
Cis 115 Education Organization -- snaptutorial.com
Cis 115   Education Organization -- snaptutorial.comCis 115   Education Organization -- snaptutorial.com
Cis 115 Education Organization -- snaptutorial.comDavisMurphyB99
 
Cis 115 Enhance teaching / snaptutorial.com
Cis 115  Enhance teaching / snaptutorial.comCis 115  Enhance teaching / snaptutorial.com
Cis 115 Enhance teaching / snaptutorial.comHarrisGeorg51
 

What's hot (20)

Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
C # (2)
C # (2)C # (2)
C # (2)
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Awt
AwtAwt
Awt
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Csphtp1 05
Csphtp1 05Csphtp1 05
Csphtp1 05
 
CIS 115 Exceptional Education - snaptutorial.com
CIS 115   Exceptional Education - snaptutorial.comCIS 115   Exceptional Education - snaptutorial.com
CIS 115 Exceptional Education - snaptutorial.com
 
project report in C++ programming and SQL
project report in C++ programming and SQLproject report in C++ programming and SQL
project report in C++ programming and SQL
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
Awt controls ppt
Awt controls pptAwt controls ppt
Awt controls ppt
 
OOP program questions with answers
OOP program questions with answersOOP program questions with answers
OOP program questions with answers
 
Csphtp1 13
Csphtp1 13Csphtp1 13
Csphtp1 13
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
 
CIS 115 Education Specialist / snaptutorial.com
CIS 115  Education Specialist / snaptutorial.comCIS 115  Education Specialist / snaptutorial.com
CIS 115 Education Specialist / snaptutorial.com
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
02 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_0202 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_02
 
Cis 115 Education Organization -- snaptutorial.com
Cis 115   Education Organization -- snaptutorial.comCis 115   Education Organization -- snaptutorial.com
Cis 115 Education Organization -- snaptutorial.com
 
Cis 115 Enhance teaching / snaptutorial.com
Cis 115  Enhance teaching / snaptutorial.comCis 115  Enhance teaching / snaptutorial.com
Cis 115 Enhance teaching / snaptutorial.com
 

Similar to Java calculator

Psuedocode1, algorithm1, Flowchart1.pptx
Psuedocode1, algorithm1, Flowchart1.pptxPsuedocode1, algorithm1, Flowchart1.pptx
Psuedocode1, algorithm1, Flowchart1.pptxMattFlordeliza1
 
Mocks Enabling Test-Driven Design
Mocks Enabling Test-Driven DesignMocks Enabling Test-Driven Design
Mocks Enabling Test-Driven DesignAlexandre Martins
 
Project: Call Center Management
Project: Call Center ManagementProject: Call Center Management
Project: Call Center Managementpritamkumar
 
Csphtp1 07
Csphtp1 07Csphtp1 07
Csphtp1 07HUST
 
XMetaL Dialog Odds & Ends
XMetaL Dialog Odds & EndsXMetaL Dialog Odds & Ends
XMetaL Dialog Odds & EndsXMetaL
 
Csphtp1 12
Csphtp1 12Csphtp1 12
Csphtp1 12HUST
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Below I have 2 microservices that compile very well- I need help inte.pdf
Below I have 2 microservices that compile very well-  I need help inte.pdfBelow I have 2 microservices that compile very well-  I need help inte.pdf
Below I have 2 microservices that compile very well- I need help inte.pdfrdzire2014
 
wcmc_practicals
wcmc_practicalswcmc_practicals
wcmc_practicalsMannMehta7
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesDavid Voyles
 
Cis 115 Education Organization / snaptutorial.com
Cis 115 Education Organization / snaptutorial.comCis 115 Education Organization / snaptutorial.com
Cis 115 Education Organization / snaptutorial.comBaileya126
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
Seminar 2 coding_principles
Seminar 2 coding_principlesSeminar 2 coding_principles
Seminar 2 coding_principlesmoduledesign
 
Nokia Asha App Development - Part 2
Nokia Asha App Development - Part 2Nokia Asha App Development - Part 2
Nokia Asha App Development - Part 2Marlon Luz
 
Gui builder
Gui builderGui builder
Gui builderlearnt
 

Similar to Java calculator (20)

Psuedocode1, algorithm1, Flowchart1.pptx
Psuedocode1, algorithm1, Flowchart1.pptxPsuedocode1, algorithm1, Flowchart1.pptx
Psuedocode1, algorithm1, Flowchart1.pptx
 
Mocks Enabling Test-Driven Design
Mocks Enabling Test-Driven DesignMocks Enabling Test-Driven Design
Mocks Enabling Test-Driven Design
 
Project: Call Center Management
Project: Call Center ManagementProject: Call Center Management
Project: Call Center Management
 
Exercises
ExercisesExercises
Exercises
 
Csphtp1 07
Csphtp1 07Csphtp1 07
Csphtp1 07
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
XMetaL Dialog Odds & Ends
XMetaL Dialog Odds & EndsXMetaL Dialog Odds & Ends
XMetaL Dialog Odds & Ends
 
Csphtp1 12
Csphtp1 12Csphtp1 12
Csphtp1 12
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Below I have 2 microservices that compile very well- I need help inte.pdf
Below I have 2 microservices that compile very well-  I need help inte.pdfBelow I have 2 microservices that compile very well-  I need help inte.pdf
Below I have 2 microservices that compile very well- I need help inte.pdf
 
Chapter9 r studio2
Chapter9 r studio2Chapter9 r studio2
Chapter9 r studio2
 
SPF WinForm Programs
SPF WinForm ProgramsSPF WinForm Programs
SPF WinForm Programs
 
wcmc_practicals
wcmc_practicalswcmc_practicals
wcmc_practicals
 
Using prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile servicesUsing prime[31] to connect your unity game to azure mobile services
Using prime[31] to connect your unity game to azure mobile services
 
Cis 115 Education Organization / snaptutorial.com
Cis 115 Education Organization / snaptutorial.comCis 115 Education Organization / snaptutorial.com
Cis 115 Education Organization / snaptutorial.com
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Seminar 2 coding_principles
Seminar 2 coding_principlesSeminar 2 coding_principles
Seminar 2 coding_principles
 
Nokia Asha App Development - Part 2
Nokia Asha App Development - Part 2Nokia Asha App Development - Part 2
Nokia Asha App Development - Part 2
 
Gui builder
Gui builderGui builder
Gui builder
 
First c program
First c programFirst c program
First c program
 

Recently uploaded

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 

Recently uploaded (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 

Java calculator

  • 1. Java CalculatorChapter 6 Sarah McNellis
  • 2. Entering Variables into the Calculator Application Code mean Displays the code to begin the Calculator application. Lines 17 through 25 declare the private variables.
  • 3. Entering Variables into theCalculator Application Import Statements import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import java.text.DecimalFormat; import javax.swing.JOptionPane; public class Calculator extends Frame implements ActionListener { private Button keys[]; private Panel keypad; private TextField lcd; private double op1; private boolean first; private boolean foundKey; private boolean clearText; private int lastOp; private DecimalFormat calcPattern; Class Header Private Variables Declared
  • 4. Using Menus in the Calculator Application code means Displays the beginning of the Calculator() constructor method also the code in the slide also shows the code that to set up the menu system. These are some of the meaning of the codes
  • 5. Using Menus in the Calculator Application Constructor Method header public Calculator() { // create an instance of the menu MenuBar mnubar = new MenuBar(); setMenuBar(mnuBar); // construct and populate the File Menu Menu mnuFile = new Menu("File", true); setMenuBar(mnuBar); MenuItem mnuFileExit = new MenuItem("Exit"); mnuFile.and(mnuFileExit); Code to create Menu bar Code to create File menu
  • 6. Using Menus in the Calculator Application Continue // construct and populate the Edit menu Menu mnuEdit = new Menu("Edit", true); mnuBar.and(mnuEdit); MenuItem mnuEditClear = new MenuItem("Clear"); mnuEdit.and(mnuEditClear); mnuEdit.insertSeparator(1); MenuItem mnuEditCopy = new MenuItem("Copy"); mnuEdit.and(mnuEditCopy); MenuItem mnuEditPaste = new MenuItem("Paste"); mnuEdit.and(mnuEditPaste); // construct and populate the About menu Menu mnuAbout = new Menu("About", true); mnuBar.and(mnuAbout); MenuItem mnuAboutCalculator = new MenuItem("About Calculator"); mnuAbout.add(mnuAboutCalculator); Code to create Edit menu Code to create About menu
  • 7. Using Menus in the Calculator Application Continue // add the ActionListener to each menu item mnuFileExit.addActionListener(this); mnuEditClear.addActionListener(this); mnuEditCopy.addActionListener(this); mnuEditPaste.addActionListener(this); mnuAboutCalculator.addActionListener(this); // assign an ActionCommand to each menu item mnuFileExit.setActionCommand("Exit"); mnuEditClear.setActionCommand("Clear"); mnuEditCopy.setActionCommand("Copy"); mnuEditPaste.setActionCommand("Paste"); mnuAboutCalculator.setActionCommand("About"); addActionListener() Methods for each menu item setActionCommand() methods for each menu item
  • 8. Initializing the Calculator Variables code means It display the code to set initial values for the Calculator application.
  • 9. Initializing the Calculator Variables // construct components and initialize beginning values lcd = new TextField(20); lcd.setEditable(false); keypad = new Panel(); keys = new Button[16]; first = true; op1 = 0.0; clearText = true; lastOp= 0; calcPattern = new DecimalFormat("########.########"); Code to initialize variables
  • 10. Creating the Keypad code means Displays the code to construct and label the keypad buttons, as well as the method to establish the GridLayout to organize the buttons.
  • 11. Creating the Keypad // construct and assign captions to the Buttons for (int i=0; i<=9; i++) key[i] = new Button(String.valueOf(i)); keys[10] = new Button("/"); keys[11] = new Button("*"); keys[12] = new Button("-"); keys[13] = new Button("+"); keys[14] = new Button("="); keys[15] = new Button("."); // set Frame and keypad layout to grid layout setLayout(new BorderLayout()); keypad.setLayout(new GridLayout(4,4,10,10)); Code to construct Buttons using array setLayout() methods set BorderLayout for Frame and GridLayout for keypad
  • 12. Adding components to the interface code means Displays the code to add the 16 buttons to the panel using the four-row, four-column grid. Line comments within the code will help you understand how each loop and add method takes its turn creating buttons in the keypad.
  • 13. Adding components to the interface for (int i=7; i<=10; i++) // 7, 8, 9, divide keypad.add(keys[i]); for (int i=4; i<=6; i++) // 4, 5, 6 keypad.add(keys[i]); keypad.add(keys[11]); // multiply for (int i=1; i<=3; i++) // 1, 2, 3 keypad.add(keys[i]); keypad.add(keys[12]); // subtract keypad.add(keys[0]); // 0 key for (int i=15; i>=13; i--) keypad.add(keys[i]); // decimal point, =, add (+) keys Code to add buttons keypad
  • 14. Continuation of adding components to the Interface code means It displays the code to add the ActionListener to each of the Buttons.
  • 15. Continue adding componentsto the Interface Code to add Buttons to keypad for (int i=0; i<keys.length; i++) keys[i].addActionListener(this); add(lcd, BorderLayout.NORTH); add(keypad, BorderLayout.CENTER); Lcd TextField and keypad Panel components Added to frame
  • 16. Coding the addWindowListenerMethod means It displays the code to add a WindowListener for the Frame
  • 17. Coding the addWindowListenerMethod Creates occurrence Of windowAdapter() class addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); }// end of constructor method addWindowListener() method Overrides windowClosing() method Brace to add method
  • 18. Searching for the Exitand Clear Commands code means Displays the code used to search to menu items for a click. During program execution, the ActionCommand of any click in the interface, menu, or button will be stored in the variable arg.
  • 19. Searching for the Exitand Clear Commands ActionPerformed() Method header public void actionPerformed(ActionEvent e) { //test for menu item clicks String arg = e.getActionCommand(); if (arg == "Exit") System.exit(0); if (arg == "Clear") { clearText = true; first = true; op1 = 0.0; lcd.setText("") lcd.requestFocus(); } Tests For Exit command Code to exit program Tests for Clear command Code to clear Number displayed in Lcd TextField and Reset initial values
  • 20. Searching for the Copy and Paste Commands code means It displays the code executed if the user clicks Copy or Paste on the Edit menu.
  • 21. Searching for the Copy and Paste Commands Code Tests if Copy Command clicked if (arg == "Copy") { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection centents = new StringSelection(lcd.getText()); cb.setContents(contents, null); } if (arg == "Paste") { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable content = cb.getContents(this); try { String s = (String)content.getTransferData(DataFlavor.stringFlavor); lcd.setText(calcPattern.format(Double.parseDouble(s))); } catch (Throwable exc) { lcd.setText("") } } Code to copy display To clipboard Test if Paste command clicked Code to paste data From clipboard
  • 22. Searching for the About Calculator Command mean in code It display the code to search for the Calculator command.
  • 23. Searching for the About Calculator Command Code Test if the About Command was clicked if (arg == "About") { String message = "Calculator ver. 1.0OpenExhibit SoftwareCopyright 2007All right reserved"; JOptionPane.showMessageDialog(null ,message,"About Calculator", JOptionPane.INFORMATION_MESSAGE); } Code to display About Calculator Message box
  • 24. Searching the Numeric Buttons Code means It displays the code to search the array of buttons to determine which button the user clicked and to add functionality to the numeric buttons and the decimal point in the actionPerformed() method.
  • 25. Searching the Numeric Buttons Code // test for button clicks foundKey = false; // search for the clicked key for (int i=0; i<keys.length && !foundKey; i++) { if(e.getSource() == keys[i]) { foundKey = true; switch(i) { // number and decimal point buttons case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 15: if(clearText) { lcd.setText(""); clearText = false; } lcd.setText(lcd.getText() + keys[i].getLabel()); break; It displays the code To test for button click Of the numeric Buttons or the Decimal point button
  • 26. Searching for the First Operator ButtonClick Code means It displays the code to search the array and add functionality to the operator buttons within the actionPerformed() method.
  • 27. Searching for the First Operator ButtonClick Code // operator buttons case 10: case 11: case 12: case 13: case 14: clearText = true; if (first) // first operand { if(lcd.getText().length()==0) op1 = 0.0; else op1 = Double.parseDouble(lcd.getText()); first = false; clearText = true; lastOp = i; //save last operator } It displays the code to Handle the first operator Button click in a calculation
  • 28. Searching for Subsequent OperatorClicks code means This displays is the code that executes on subsequent operator click
  • 29. Searching for Subsequent OperatorClicks code else // second operand { switch(lastOp) { case 10: // divide button op1 /= Double.parseDouble(lcd.getText()); break; case 11: // multiply button op1 *= Double.parseDouble(lcd.getText()); break; case 12: // minus button op1 -= Double.parseDouble(lcd.getText()); break; case 13: // plus button op1 += Double.parseDouble(lcd.getText()); break; } // end of switch(lastOp) lcd.setText(calcPattern.format(op1)); clearText = true; The code to handle Subsequent operator Button click in a calculation
  • 30. Searching for the Equal Button code means When the user specifically clicks the equal button, the lastOp variable is assigned a value of 14, which is the index number of the equal button.
  • 31. Searching for the Equal Button code The cod to handle a click of The equal button, Represented by the subscript 14 in the array. if(i==14) first = true;//equal button else lastOp = i; // save last operator } // end else break; } // end of switch(i) } // end of if } // end of for } // end of actionPerformed
  • 32. Coding the main() Method for the Calculator class coding means The main() method for the Calculator application constructs an instance of the Calculator class and then sets three attributes.
  • 33. Coding the main() Method for the Calculator class public static void main(String args[]) { // set frame properties Calculator f = new Calculator(); f.setTitle("Calculator Application"); f.setBounds(200,200,300,300); f.setVisible(true); // set image properties and add to frame Image icon = Toolkit.getDefaultToolkit().getImage("calcImage.gif"); f.setIconImage(icon); } // end of main }// end of class
  • 34. Print screen of the Calculator
  • 35. Link to the file Calculator
  • 36. Work Cited Shelly Cashman Starks Mick: “Java Programming comprehensive Concepts and Techniques” third Edition print 2006