Our first program is a simple calculator, which will carry out the arithmetic operations of adding, subtracting, multiplying and dividing numbers.

Similar documents
1 Using the NetBeans IDE

3 Multiple windows. Chapter 3: Multiple windows 57

In this chapter we will examine arrays, and the ways that they can be used in combination with loop structures to process data in programs.

10 Object oriented programming

search value 94 not found

4 Decision making in programs

Further names can be linked by pointers in the records. A null pointer value indicates the end of the sequence. location 0 location 1 location 2

Lecture (06) Java Forms

In this section you will learn some simple data entry, editing, formatting techniques and some simple formulae. Contents

13 Recursion. Chapter 13: Recursion 359

Excel 2016: Part 1. Updated January 2017 Copy cost: $1.50

FRONTPAGE STEP BY STEP GUIDE

EXCEL BASICS: MICROSOFT OFFICE 2007

EXCEL PRACTICE 5: SIMPLE FORMULAS

Using Adobe Photoshop

Prepared By: Graeme Hilson. U3A Nunawading

SUM - This says to add together cells F28 through F35. Notice that it will show your result is

Using Microsoft Access

EXCEL BASICS: MICROSOFT OFFICE 2010

Some (semi-)advanced tips for LibreOffice

A Dreamweaver Tutorial. Contents Page

Learn more about Pages, Keynote & Numbers

As in the linked list, a start pointer indicates the position of the first town. The first item in the binary tree is known as the root node.

A Tutorial for Excel 2002 for Windows

Formulas Learn how to use Excel to do the math for you by typing formulas into cells.

Microsoft Excel Tutorial

Cell to Cell mouse arrow Type Tab Enter Scroll Bars Page Up Page Down Crtl + Home Crtl + End Value Label Formula Note:

Creating labels in Ticket 2000.

Section 18. Advanced Cell Formatting

Functional Skills. Entry 3 to Level 2. Spreadsheets 2010 Version Information

2. Formulas and Series

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

IGCSE ICT Section 16 Presentation Authoring

Getting Started with. Office 2008

Excel. Spreadsheet functions

Watch the video below to learn more about creating formulas in Excel. *Video removed from printing pages. Mathematical operators

Setting Up the Fotosizer Software

Microsoft Excel 2013: Part 3 More on Formatting Cells And Worksheet Basics. To apply number formatting:

Entering Data in the Spreadsheet

Premium POS Pizza Order Entry Module. Introduction and Tutorial

Rev. B 12/16/2015 Downers Grove Public Library Page 1 of 40

The first time you open Word

A Frontpage Tutorial. Contents Page

Microsoft Excel Microsoft Excel

Application of Skills: Microsoft Excel 2013 Tutorial

M i c r o s o f t E x c e l A d v a n c e d P a r t 3-4. Microsoft Excel Advanced 3-4

Game Design Unity Workshop

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 2 TEXT FORMATTING

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

INTRODUCTION... 1 UNDERSTANDING CELLS... 2 CELL CONTENT... 4

Answer on question #61311, Programming & Computer Science / Java

Excel Tutorial 1: Getting Started with Excel

Introduction to the workbook and spreadsheet

MultiQ Products AB reserves the right to make changes to this document and to product specifications without prior notice.

Using Microsoft Excel

Microsoft Excel 2007

Excel 2013 Part 2. 2) Creating Different Charts

The Newsletter will contain a Title for the newsletter, a regular border, columns, Page numbers, Header and Footer and two images.

Plotting Points. By Francine Wolfe Professor Susan Rodger Duke University June 2010

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

WORD 2016 INTERMEDIATE Page 1. Word 2016 Intermediate. North American Edition SAMPLE

Microsoft Excel Important Notice

Chapter 13 Creating a Workbook

EXCEL 2007 TIP SHEET. Dialog Box Launcher these allow you to access additional features associated with a specific Group of buttons within a Ribbon.

Excel Foundation Quick Reference (Windows PC)

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

POS Designer Utility

Designing Forms in Access

Introduction to Microsoft Excel 2010

Excel 2016 Basics for Windows

Interface. 2. Interface Adobe InDesign CS2 H O T

Excel Select a template category in the Office.com Templates section. 5. Click the Download button.

Rocket Theme. User Guide

EXCEL 2013 FDLRS SUNRISE

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

Survey of Math: Excel Spreadsheet Guide (for Excel 2016) Page 1 of 9

Formatting Text. 05_Format rd July 2000

The Menu and Toolbar in Excel (see below) look much like the Word tools and most of the tools behave as you would expect.

Computer Nashua Public Library Advanced Microsoft Word 2010

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Excel Level 1

Section 3. Formulas. By the end of this Section you should be able to:

Within the spreadsheet, columns are labeled with letters and rows are labeled with numbers.

Intermediate Excel 2003

INFORMATION SHEET 24002/1: AN EXCEL PRIMER

How to Archive s in Outlook 2007

WinView. Getting Started Guide

Microsoft Excel 2010 Handout

Advanced Microsoft Word 2010

E D T 3 2 E D T 3. Slide 1

Dreamweaver MX Overview. Maintaining a Web Site

Status Bar: Right click on the Status Bar to add or remove features.

Lesson 5 Styles, Tables, and Frames

Basic tasks in Excel 2013

Microsoft Expression Web is usually obtained as a program within Microsoft Expression Studio. This tutorial deals specifically with Versions 3 and 4,

ECDL Module 4 REFERENCE MANUAL

Creating Reports in Access 2007 Table of Contents GUIDE TO DESIGNING REPORTS... 3 DECIDE HOW TO LAY OUT YOUR REPORT... 3 MAKE A SKETCH OF YOUR

DataSweet also has a whole host of improvements which are not covered in this document.

Chapter 3: The IF Function and Table Lookup

Transcription:

Chapter 2: Calculations 29 2 Calculations Most computer programs need to carry out calculations, for example: with money, quantities of materials, or dates and times. In this chapter, we will examine how the Java programming language handles numbers. Our first program is a simple calculator, which will carry out the arithmetic operations of adding, subtracting, multiplying and dividing numbers. Go to the File menu in NetBeans and Close all projects. Select the New Project option and check that Java / Java application is highlighted, then click the Next button. Give the Project Name as calculate, and un-tick the Create Main Class option: Click the Finish button to return to the NetBeans main page. Click the Projects tab at the left of the page, then right-click on the calculate project icon to open a drop-down menu. Select New, then JFrame Form. Set the Class Name as calculate, and the Package as calculatepackage:

30 Java Programming for A-level Computer Science Return to the NetBeans design screen. Locate the Label component in the Palette, and drag and drop a label onto the form. Notice that grey bars are shown linked to the label component which are not required. Move to an empty area of the form and right-click to show the drop-down menu. Select Set Layout / Absolute Layout: Right-click on the label which you placed on the form, and use the Edit Text option to change the caption to the letter 'A': Increase the size of the label text by clicking on the font property in the Properties window, then resetting the font size to 14.

Chapter 2: Calculations 31 Locate the Text Field component in the Palette. Drag and drop a text field next to the label: Right-click on the text field. Select the Change Variable Name option from the drop-down menu, and give the name 'txta'. Right-click again and select Edit Text. Delete the caption from the text field. Add another label and text field, naming the text field as 'txtb' and deleting the text caption. Finally add a button with the caption 'A + B =', and a text field with the name 'txtadd'. Delete the caption from the text field

32 Java Programming for A-level Computer Science When the program runs, we would like to enter numbers in the text fields labelled A and B, click the button to add the numbers together, then display the answer in the txtadd text field. The first stage is to set up variables. We can think of these as memory boxes which will store the two numbers entered, and the answer when it is calculated. We will set the data type as integer, which means 'a whole number'. Click the Source tab to display the program code. Near the top of the program, just below the start of the calculate class, add the line of code shown below: package calculatepackage; public class calculate extends javax.swing.jframe int A, B, answer; public calculate() initcomponents(); Click the Design tab to return to the design screen, then double click the 'A + B =' button. The Code page will open and you will see that an empty button click method has been created. Add lines of code as shown: private void btnaddactionperformed(java.awt.event.actionevent evt) A=Integer.parseInt(txtA.getText()); B=Integer.parseInt(txtB.getText()); answer=a+b; txtadd.settext(integer.tostring(answer)); Quite a lot is going on here! The line: A = Integer.parseInt( txta.gettext( ) ); is telling the program to collect a text entry from the text field txta, then convert this to an integer number and store it as the variable A. The number B is collected in a similar way. The line: answer = A+B; adds the numbers together and stores the result as the variable called answer. Finally, the answer is displayed in the text field txtadd by the line: txtadd.settext( Integer.toString( answer ) ); The term 'string' refers to data in text format. The integer number must be converted to text before it can be displayed in a text field.

Chapter 2: Calculations 33 The full sequence can be represented as: input the data in text format convert the text to numbers carry out the calculation convert the answer back to text format display the answer in the text field We are now ready to test the program. Click the green Run button, and accept calculatepackage.calculate as the main class: The form displays the labels, text fields and button. However, the normal Windows colour scheme is not used and the window size has not been set correctly:

34 Java Programming for A-level Computer Science Close the program and return to the NetBeans editing screen. Select the Source tab to move to the program code window, then reset "Nimbus" to "Windows" in the main method: public static void main(string args[]) try for (javax.swing.uimanager.lookandfeelinfo info : javax.swing.uimanager.getinstalledlookandfeels()) if ("Windows".equals(info.getName())) javax.swing.uimanager.setlookandfeel(info.getclassname()); break; catch (ClassNotFoundException ex) Return to the Design page. Click on the form, then go to the Code section of the Properties window. Select the Form Size Policy / Generate Resize Code option: Re-run the program. The standard Windows colour scheme will now be used, and window size should be correct.

Chapter 2: Calculations 35 Test the addition function by entering two whole numbers, then clicking the button: When software is in use, it is not unusual for mistakes to be made when entering data. For example, the user might accidentally enter a letter instead of a number. Let's investigate what would happen in this case. Enter some letters, then click the button: You will find that nothing happens in the program window, although error messages appear in a window at the bottom of the NetBeans editing page. The program knows that the data entered should be an integer number, and anything else is ignored. However, it would be better to give a warning in the program that an error has occurred - we can do this by displaying a pop-up message box on the screen. Close the program window and click the Source tab to show the program code. Add a line near the top of the program to load some extra code needed to create the message box: package calculatepackage; import javax.swing.joptionpane; public class calculate extends javax.swing.jframe

36 Java Programming for A-level Computer Science Scroll down the program listing to find the btnaddactionperformed method which you produced earlier. We can now add a try...catch structure, as shown below: When the program runs, the computer will attempt to carry out the calculation. If an error is found in the number format, the catch block will operate. This will display a pop-up message box to warn the user. Add these lines of code to the method, then run the program. private void btnaddactionperformed(java.awt.event.actionevent evt) try A=Integer.parseInt(txtA.getText()); B=Integer.parseInt(txtB.getText()); answer=a+b; txtadd.settext(integer.tostring(answer)); catch(numberformatexception e) JOptionPane.showMessageDialog(calculate.this, "Incorrect number format"); If letters are now entered instead of numbers, the message box should appear:

Chapter 2: Calculations 37 We can now extend our simple calculation program to carry out the other arithmetic operations: subtracting, multiplying and dividing. The program we have written so far uses integers, whole numbers, to store the input values and the answer. This could lead to problems when we divide numbers, as the answer is unlikely to be a whole number for example: if 13 is divided by 5. In any case, we may wish to carry out calculations using decimal fractions such as: 3.142. Fortunately, there is a simple solution we can change the program to use the double data type which handles decimal fractions. Close the program window and click the Source tab to go to the program code page. Change the variable type to double at the start of the program. public class calculate extends javax.swing.jframe double A, B, answer; public calculate() initcomponents(); We also need to change Integer to Double each time it occurs in the btnadd ActionPerformed method: private void btnaddactionperformed(java.awt.event.actionevent evt) try A=Double.parseDouble(txtA.getText()); B=Double.parseDouble(txtB.getText()); answer=a+b; txtadd.settext(double.tostring(answer)); catch(numberformatexception e) JOptionPane.showMessageDialog(calculate.this, "Incorrect number format"); Run the program and check that addition can now be carried out with decimal numbers:

38 Java Programming for A-level Computer Science We can now set up buttons and text fields for subtracting, multiplying and dividing. Change the names of the buttons and text fields to: btnsubtract txtsubtract btnmultiply txtmultiply btndivide txtdivide Delete the text entries from the text fields, then drag the text field boxes to the sizes required. Double click the "A B =" button to create an empty button click method. Copy and paste the code from the btnaddactionperformed method, just changing the calculation and output lines as shown below: private void btnsubtractactionperformed(java.awt.event.actionevent evt) try A=Double.parseDouble(txtA.getText()); B=Double.parseDouble(txtB.getText()); answer=a-b; txtsubtract.settext(double.tostring(answer)); catch(numberformatexception e) JOptionPane.showMessageDialog(calculate.this, "Incorrect number format");

Chapter 2: Calculations 39 Run the program and carry out some subtractions using decimal numbers. You will probably discover a problem: calculations using double numbers are sometimes not exactly accurate! The size of the text field has been increased to demonstrate this. Double numbers are stored using a method called floating point format. This has the advantage that very large and very small numbers can be stored in a compact way which saves memory space, so we generally accept the problem of slight inaccuracy in the final decimal place. Close the program window and return to the NetBeans editing screen. We can easily display an accurate answer by limiting the number of decimal places. Change the output line to include the formatting instruction "%.2f". This will produce an answer to two decimal places. private void btnsubtractactionperformed(java.awt.event.actionevent evt) try A=Double.parseDouble(txtA.getText()); B=Double.parseDouble(txtB.getText()); answer=a-b; txtsubtract.settext(string.format("%.2f",answer)); catch(numberformatexception e) JOptionPane.showMessageDialog(calculate.this, "Incorrect number format");

40 Java Programming for A-level Computer Science Re-run the program and check that a correct answer is now displayed. Close the program window and return to the Design screen. Edit the btnadd( ) method to format the output to two decimal places. private void btnaddactionperformed(java.awt.event.actionevent evt) try A=Double.parseDouble(txtA.getText()); B=Double.parseDouble(txtB.getText()); answer=a+b; txtadd.settext(string.format("%.2f",answer)); catch(numberformatexception e) Create button click methods for the two remaining buttons. Add program code to carry out multiplication and division. Remember to change the calculation lines to use the operators '*' and '/' for multiplication and division: private void btnmultiplyactionperformed(java.awt.event.actionevent evt) try A=Double.parseDouble(txtA.getText()); B=Double.parseDouble(txtB.getText()); answer=a*b; txtmultiply.settext(string.format("%.2f",answer)); catch(numberformatexception e) JOptionPane.showMessageDialog(calculate.this, "Incorrect number format");

Chapter 2: Calculations 41 Carry out tests on the program. To be certain that the program is working correctly, you should check the answers independently by means of a calculator or spreadsheet. One final improvement is to add a Clear button which will clear all the text fields, ready for the next calculation. Right-click the button to edit the caption to 'Clear', then rename the button as btnclear.

42 Java Programming for A-level Computer Science Double click the Clear button and add lines of code to the method: private void btnclearactionperformed(java.awt.event.actionevent evt) txta.settext(""); txtb.settext(""); txtadd.settext(""); txtsubtract.settext(""); txtmultiply.settext(""); txtdivide.settext(""); Run the finished program and check that the text fields can be cleared correctly. We have now discovered a lot about the way that Java handles calculations, and are ready to use these techniques in a more realistic application: A company manufactures rectangular water storage tanks from sheet metal. The bottom and side panels of the tank are welded together without any overlap. A program is required which will input: length L width W height H of the tank, then output: the maximum volume of water which the tank could hold the area of the sheet metal required to construct the tank.

Chapter 2: Calculations 43 Use the NetBeans File menu option to Close All Projects, then click the New Project option. Check that Java / Java Application is selected then click the Next button. Create a project with the name watertank. Use the Browse button to choose the location where you want the project to be stored. Make sure that the Create Main Class option is not ticked: Return to the NetBeans editing page. Click the Projects tab at the left of the page, then right click on the watertank project icon to open a drop-down menu. Select New, then JFrame Form. Set the Class Name as watertank, and the Package as watertank Package:

44 Java Programming for A-level Computer Science Return to the NetBeans editing page. Before beginning work on the application, we will carry out the three steps necessary to ensure the correct behaviour of the program: Right click on the form, and select Set layout / Absolute layout. Go to the Properties window on the bottom right of the screen and click the Code tab. Select the option: Form Size Policy / Generate pack() / Generate Resize code. Click the Source tab above the design window to open the program code. Locate the main method. Use the + icon to open the program lines and change the parameter Nimbus to Windows. Run the program and accept the main class which is offered. Check that a blank window appears and has the correct size and colour scheme. Close the program and return to the NetBeans editing screen. This program again uses a picture image, so we will create a resources folder. Go to watertank in the Projects window. Right-click on watertankpackage and select New / Java Package. Give the Package Name as watertankpackage.resources: Return to the NetBeans editing page. Click the Design tab to move to the form layout view. Before continuing, obtain or create a diagram of a water tank similar to the diagram at the start of this section. Save this in JPG format. Select the Label component in the Palette, then drag and drop a label onto the form. Go to the Properties window and locate the icon property. Click the ellipsis ( ) symbol at the right of the icon property line.

Chapter 2: Calculations 45 Use the Import to Project button to upload the diagram image. Check that this is selected on the File line: Return to the NetBeans editing page. The image of the water tank should be displayed. If necessary, drag the image into the correct position on the form. Right-click on the image and select Edit Text. Delete the text caption from the label. We can now work on the first stage of the calculation, to find the maximum volume of water which can be held in the tank. This will be given by the formula: volume = length * width * height

46 Java Programming for A-level Computer Science Set up labels, text fields and a Calculate button as shown below. Rename the button as btncalculate. If necessary, drag the form wider so that there is space for all the components. Give names to the text fields: txtlength txtwidth txtheight txtvolume Click the Source tab to show the program code. Add a line near the top of the program to load extra code to create a message box: package watertankpackage; import javax.swing.joptionpane; public class calculate extends javax.swing.jframe Just below, at the start of the watertank class, add the variables: public class watertank extends javax.swing.jframe double L, W, H, volume, area; public watertank() initcomponents();

Chapter 2: Calculations 47 Click the Design tab to return to the design page. Double click the Calculate button to create an empty method. Add lines of program code: private void btncalculateactionperformed(java.awt.event.actionevent evt) try L=Double.parseDouble(txtLength.getText()); W=Double.parseDouble(txtWidth.getText()); H=Double.parseDouble(txtHeight.getText()); volume = L * W * H; txtvolume.settext(string.format("%.2f",volume)); catch(numberformatexception e) JOptionPane.showMessageDialog(waterTank.this, "Incorrect number format"); As in the previous program, we will output the answer to two decimal places, and use a try...catch block to display a message box if data is entered incorrectly. Run the program. Use test data to check that the volumes of different sizes of tank can be calculated correctly. Verify the results independently using a calculator or spreadsheet. Close the program window and return to the NetBeans editing screen.

48 Java Programming for A-level Computer Science The final stage of the program is to calculate the area of metal required to construct the tank. Add a label and text field for displaying the result. Name the text field as txtarea: We need to give some thought to how the area of metal should be calculated. Imagine the tank surface opened out into flat shape, known in mathematics as a net: length height L * H height W * H L * W W * H width L * H From the diagram, we can see that the total area of metal required is the total of: This could be written as a formula: base area = length * width 2 sides area = length * height 2 sides area = width * height volume = (L * W) + 2 * (L * H) + 2 * (W * H)

Chapter 2: Calculations 49 Return to the btncalculateactionperformed method in the program listing. Add lines to carry out the area calculation and display the result in the txtarea text field: private void btncalculateactionperformed(java.awt.event.actionevent evt) try L=Double.parseDouble(txtLength.getText()); W=Double.parseDouble(txtWidth.getText()); H=Double.parseDouble(txtHeight.getText()); volume = L * W * H; txtvolume.settext(string.format("%.2f",volume)); area = (L*W) + 2*(L*H) + 2*(W*H); txtarea.settext(string.format("%.2f",area)); catch(numberformatexception e) JOptionPane.showMessageDialog(waterTank.this, "Incorrect number format"); Run the program and check that area of metal can be calculated correctly for different sizes of tank:

50 Java Programming for A-level Computer Science For the final program in this section, we will create an application for use in a Fast Food Restaurant, to calculate the total cost of customers' orders. Close all current projects, then select New Project from the File menu of the NetBeans editor. Set the Project Name to fastfood, and ensure that Create Main Class is not ticked: Return to the NetBeans editing page. Click the Projects tab at the top left of the page, then rightclick on the fastfood project icon to open a drop-down menu. Select New, then JFrame Form. Set the Class Name as fastfood, and the Package as fastfoodpackage:

Chapter 2: Calculations 51 Click the Finish button to return to the NetBeans editor page. Right-click on the form, and select Set layout / Absolute layout. Go to the Properties window on the bottom right of the screen and click the Code tab. Select the option: Form Size Policy / Generate pack() / Generate Resize code. Click the Source tab above the design window to open the program code. Locate the main method. Use the + icon to open the program lines and change the parameter Nimbus to Windows. Run the program and accept the main class which is offered. Check that a blank window appears and has the correct size and colour scheme. Close the program and return to the editing screen. This program will again use picture images, so we will create a resources folder. Open the fastfood project structure until fastfoodpackage is reached. Right-click on fastfoodpackage and select New / Java Package. Give the Package Name as fastfoodpackage.resources: Before continuing, obtain picture images of five items which might be sold in a fast food restaurant, such as: burgers, fries, soft drink and cheesecake. Add a label to the form. Go to the Properties window and locate the icon property. Click the ellipsis (" "), then use the Import to Project button to upload the five images. Select one of the image names on the File line:

52 Java Programming for A-level Computer Science Return to the form and add four more labels. Link a picture to each label, and delete the label text: Locate the Spinner component in the Palette. Drag and drop a spinner alongside the first image. Right-click on the spinner and rename the component as spinburger or a similar suitable name.

Chapter 2: Calculations 53 Add spinners in a similar way for the remaining pictures, renaming these as: spinburgercheese, spinfries, spincoke and spincake. Also add a label for each menu item above the spinner: Complete the form by adding a button, ' ' label, and text field with the name txttotal to display the order total. Rename the button as btntotal. Also add a Reset button, which can be used to cancel values shown by the spinner components. Rename the button as btnreset.

54 Java Programming for A-level Computer Science Double click the Reset button and add lines of program code to the method: private void btnresetactionperformed(java.awt.event.actionevent evt) spinburger.setvalue(0); spinburgercheese.setvalue(0); spinfries.setvalue(0); spincoke.setvalue(0); spincake.setvalue(0); txttotal.settext(""); Run the program. Accept the main method offered. Set numbers on each of the spinner components, then click the Reset button. check that all spinners are reset to zero. Close the program window and return to the NetBeans editor. The next stage is to calculate the cost of the customer's order. Begin by going to the Source page and setting up a series of constants at the start of the fastfood class. Each line is a double number which records the price of a food item. These constants can then be used later in formulae to calculate the order cost. package fastfoodpackage; public class fastfood extends javax.swing.jframe double burgerprice = 2.70; double burgercheeseprice = 3.40; double friesprice = 1.20; double cokeprice = 1.80; double cakeprice = 1.60; public fastfood() initcomponents(); Using constants in this way is good programming practice. If the price of an item changes, the program only has to be changed in one easily accessible place, rather than the programmer having to search through the whole program for every separate occurrence of the original price. Return to the Design page and double click the Total button to create an empty button click method.

Chapter 2: Calculations 55 We will begin by adding code to calculate the cost of the first food item. Set up a variable called total and initialise this to zero. We can calculate the cost of the burgers purchased by: (number purchased) * (price) A simple way to add this amount to total is to use the '+ = ' operator. The final result is then output to the txttotal text field: private void btntotalactionperformed(java.awt.event.actionevent evt) double total=0; total += (Integer) spinburger.getvalue()*burgerprice; txttotal.settext(string.format("%.2f",total)); Run the program. Select a quantity of the first food item, then click the Total button. Check that the correct order total is shown. You may find that the spinners are only wide enough to display single digits. If your restaurant is catering for larger groups, the spinner components can be dragged wider!

56 Java Programming for A-level Computer Science Close the program and return to the Source page. Locate the btntotalactionperformed method. Add further lines of code to calculate and add the cost of each of the remaining food items. Be careful to specify the correct names for the price constants and spinners: private void btntotalactionperformed(java.awt.event.actionevent evt) double total=0; total += (Integer) spinburger.getvalue()*burgerprice; total += (Integer) spinburgercheese.getvalue()*burgercheeseprice; total += (Integer) spinfries.getvalue()*friesprice; total += (Integer) spincoke.getvalue()*cokeprice; total += (Integer) spincake.getvalue()*cakeprice; txttotal.settext(string.format("%.2f",total)); Run the program. Check that the totals for full orders are calculated correctly: