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.

Similar documents
3 Multiple windows. Chapter 3: Multiple windows 57

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

1 Using the NetBeans IDE

search value 94 not found

10 Object oriented programming

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.

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

13 Recursion. Chapter 13: Recursion 359

4 Decision making in programs

Activity: page 1/10 Introduction to Excel. Getting Started

Getting Started with Microsoft Excel 2013

The Photo Gallery. Adding a Photo Gallery Page. Adding a Photo Gallery App

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

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

Laboratory 1. Part 1: Introduction to Spreadsheets

Word 2007 Tables Part 2

GOOGLE APPS. If you have difficulty using this program, please contact IT Personnel by phone at

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

Using Microsoft Excel

Advanced Excel. Click Computer if required, then click Browse.

Using Dreamweaver. 4 Creating a Template. Logo. Page Heading. Home About Us Gallery Ordering Contact Us Links. Page content in this area

Microsoft Excel 2007 Beginning The information below is devoted to Microsoft Excel and the basics of the program.

Module 4 : Spreadsheets

FRONTPAGE STEP BY STEP GUIDE

Starting Excel application

Excel 2016 Basics for Windows

COMSC-031 Web Site Development- Part 2. Part-Time Instructor: Joenil Mistal

CROMWELLSTUDIOS. Content Management System Instruction Manual V1. Content Management System. V1

4) Study the section of a worksheet in the image below. What is the cell address of the cell containing the word "Qtr3"?

Content Creation and Management System. External User Guide 3 Question types in CCMS (an overview)

WEEK NO. 12 MICROSOFT EXCEL 2007

Getting Started With Excel

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

7. Apply a Range of Table Features

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

New Perspectives on Microsoft Excel Module 5: Working with Excel Tables, PivotTables, and PivotCharts

Free Microsoft Office 2010 training from MedCerts. Course Outline

Week 5 Creating a Calendar. About Tables. Making a Calendar From a Table Template. Week 5 Word 2010

JF MSISS. Excel Tutorial 1

GCSE CCEA GCSE EXCEL 2010 USER GUIDE. Business and Communication Systems

Microsoft Excel 2010 Handout

Photos & Photo Albums

Data. Selecting Data. Sorting Data

Tutorial 5: Working with Excel Tables, PivotTables, and PivotCharts. Microsoft Excel 2013 Enhanced

Using Reports and Graphs

Thermacam Reporter 2000 Professional Template Building Tutorial

Section 18. Advanced Cell Formatting

THE AMERICAN LAW INSTITUTE Continuing Legal Education

Creating a Website in Schoolwires

Creating Forms. Starting the Page. another way of applying a template to a page.

LORD P.C.A.A LIONS MAT.HR.SEC SCHOOL, RESERVE LINE, SIVAKASI

Unit 8. Lesson 8.1. Microsoft FrontPage. Introduction. Microsoft FrontPage-1. Microsoft FrontPage

Google Sheets: Spreadsheet basics

Excel Primer CH141 Fall, 2017

Using Microsoft Word. Working With Objects

Tutorial 1: Getting Started with Excel

4. Spreadsheet Design Features: Formatting

Labels and Envelopes in Word 2013

Microsoft Excel 2007

Application of Skills: Microsoft Excel 2013 Tutorial

Nauticom NetEditor: A How-to Guide

POS Designer Utility

Links to Activities ACTIVITY 4.1. Links to Activities Links to Activities

Beginners Guide to Snippet Master PRO

Excel Basic 1 GETTING ACQUAINTED WITH THE ENVIRONMENT 2 INTEGRATION WITH OFFICE EDITING FILES 4 EDITING A WORKBOOK. 1.

Microsoft Excel Important Notice

Section 5. Pictures. By the end of this Section you should be able to:

Excel 2016 Basics for Mac

Visual C# Program: Simple Game 3

Barchard Introduction to SPSS Marks

Excel 2010: Getting Started with Excel

Using Reports. Access 2013 Unit D. Property of Cengage Learning. Unit Objectives. Files You Will Need

Changing Button Images in Microsoft Office

FORMS. The Exciting World of Creating RSVPs and Gathering Information with Forms in ClickDimensions. Presented by: John Reamer

Introduction to Microsoft Excel 2010

Opening a Data File in SPSS. Defining Variables in SPSS

USING MICROSOFT ACCESS 2013 Guided Project 7-1

1) Merge the cells that contain the title and center the title

C omputer D riving L icence

Lecture (06) Java Forms

Glossary Unit 1: Hardware and Software

Drupal Cloud Getting Started Guide Creating a Lab site with the MIT DLC Theme

Spreadsheet Software

A Frontpage Tutorial. Contents Page

Word 3 Microsoft Word 2013

STUDENT NAME ECDL: EXCEL MR BENNELL. This is an example of how to use this checklist / evidence document

ECDL Module 4 REFERENCE MANUAL

Rev. C 11/09/2010 Downers Grove Public Library Page 1 of 41

The New York Society Library Presents:

Microsoft Office Excel

Using Microsoft Excel

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

Section 2. Advanced Cell Formatting

PowerPoint Launching PowerPointX

Excel 2016 Essentials Syllabus

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

Creating a Portfolio in LiveText

Making Your Showcase Portfolio

Creating a Spreadsheet by Using Excel

Beginner s Guide to Microsoft Excel 2002

Transcription:

Chapter 5: Loops and arrays 117 5 Loops and arrays 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. The first project is a scientific application: Monitoring of the level of pollutants in a river is carried out at regular intervals. A program is required which will: inupt the number of readings collected input each of the readings and store these for processing. The program should then output: a list of the readings the mean of the readings the maximum and minimum values recorded. In this program we will need to store readings which are entered. To do this, variables will be required. We could set up individual variables for each reading, as we have done in previous programs: int reading1; int reading 2; int readfing3; etc However, this would be very tedious, and probably impossible if there was a very large number of readings. A better approach is to use an array. This acts like a series of numbered storage boxes. The whole array is given a name, and each individual box, or element, is given an index number. Arrays in Java always begin with element 0: reading reading[0] reading[1] reading[2] reading[3] reading[4] reading[5]. reading[n] We set up the array with a line of program such as: int[ ] reading = new int[100]; In this case, we have specified that the array should have elements for storing integer whole numbers, it is to be called "reading", and it is to have 100 elements (which will be numbered 0 to 99). A design for the program is given in the flowchart on the next page.

118 Java Programming for A-level Computer Science start enter the number of readings count = 1 count = count + 1 enter reading[count] Y another reading? N total = 0 max = reading[1] min = reading[1] count = 1 display reading[count] reading[count] > max? N Y max = reading[count] count = count + 1 reading[count] < min? N Y min = reading[count] Y another reading? N display mean of the readings display maximum and minimum stop

Chapter 5: Loops and arrays 119 Close all projects, then set up a New Project. Give this the name waterquality, and ensure that the Create Main Class option is not selected. Return to the NetBeans editing page. Right-click on the waterquality project, and select New / JFrame Form. Give the Class Name as waterquality,and the Package as waterqualitypackage: Click the Finish button to return to the NetBeans editing screen. 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. Click the Design tab to move to the form layout view. Locate the Spinner component in the palette, and drag and drop this on the form. Rename the component as spinreadings. Add a label with the caption "Number of readings", and a button with the caption "Enter data". Rename the button as btnstart.

120 Java Programming for A-level Computer Science Locate the Panel component in the palette, and drag and drop this on the form. Right-click on the panel and select Layout / Absolute Layout. Rename the panel as pnlinput. Add a label to the panel and rename this as lblenterreading. (The caption for this label will be set by the program when it runs, so the default text for the label need not be changed.) Add a text field with the name txtreading, and a button with the name btnenter. Select the panel and locate the border row in the property window. Click in the right hand column to open the border style window, and select Bevel Border: Click the Source tab to open the code window. We will first set up an array to store the readings, allowing for a maximum of 100 integer values to be entered. Add variables to record the total number of readings to be entered, and a count of the number of readings entered so far. We will set the input panel to not be visible when the program first runs: public class waterquality extends javax.swing.jframe int[] pollutant = new int[100]; int totalreadings; int count; public waterquality() initcomponents(); pnlinput.setvisible(false);

Chapter 5: Loops and arrays 121 Click the Design tab to return to the form, then double click the "Enter data" button alongside the spin component to create a method. Add lines of code to the method which will: collect the number of readings from the spin component make the input panel visible initialise the count of readings entered to 1 set the label text on the panel to display the number of the reading which is currently being entered. private void btnstartactionperformed(java.awt.event.actionevent evt) totalreadings=(integer) spinreadings.getvalue(); pnlinput.setvisible(true); count=1; lblenterreading.settext("enter reading "+ Integer.toString(count)); Run the program. Set the number of readings using the spin component, then click the 'Enter data' button. Check that the panel appears, the caption 'Enter reading 1' is displayed, and a value can be entered in the text field. You may need to adjust the size of the label and text field. Close the program and return to the editing screen. Click the Design tab to go to the form, then double click the OK button to create a method. Add code which will: collect the value which has been entered in the text field, and store it in the array, increase the count of readings by one, if all the data has not yet been entered, then change the label caption to display the number of the current reading: private void btnenteractionperformed(java.awt.event.actionevent evt) pollutant[count]=integer.parseint(txtreading.gettext()); txtreading.settext(""); count++; if (count<= totalreadings) lblenterreading.settext("enter reading "+ Integer.toString(count));

122 Java Programming for A-level Computer Science We must now consider what will happen when data entry is completed. The specification asks for the readings to be displayed in a list, along with the mean, maximum and minimum values. To do this we will add another panel to the form. Click the Design tab to move to the form layout view, then drag and drop a Panel component below the input panel. Rename the panel as pnloutput. Go to the border property line and select Bevel Border. Add a text area to the panel and name this as txtoutput: It would be best if this panel is not visible when the program begins. Click the Source tab to open the program code window. Locate the waterquality( ) method, and add a line to set the visible property for the panel to false: public waterquality() initcomponents(); pnlinput.setvisible(false); pnloutput.setvisible(false); Locate the btnenteractionperformed method which you began to develop earlier. We can now add lines of program code which will operate when the user enters the final reading. These lines of code will: make the input panel close and the output panel appear, define a string variable 's' which will be used to display the output text, use a loop to collect each of the readings from the pollutant[ ] array and add it to s, so that they will be displayed in the output list.

Chapter 5: Loops and arrays 123 Add the ELSE block to the method: private void btnenteractionperformed(java.awt.event.actionevent evt) pollutant[count]=integer.parseint(txtreading.gettext()); txtreading.settext(""); count++; if (count<= totalreadings) lblenterreading.settext("enter reading "+ Integer.toString(count)); else pnlinput.setvisible(false); pnloutput.setvisible(true); String s=""; s+="readings: \n"; for (int i=1; i<=totalreadings; i++) s+=" "+ Integer.toString(pollutant[i])+"\n"; txtoutput.settext(s); Run the program. Set the number of readings which will be entered, then click the "Enter data" button. The input panel should appear, prompting you to enter each of the readings in turn. When the correct number of readings have been entered, the output panel should open and display a list of the readings:

124 Java Programming for A-level Computer Science Close the program and return to the Source code editing window. Notice the structure of the loop control line: for (int i = 1; i <= totalreadings; i++) This is made up of three parts, separated by semi-colons. The first part: int i = 1; defines a local variable i which will be used as a counter while the loop is repeating. We are giving this variable an initial value of 1. The next part: i <= totalreadings; tells the computer to keep repeating the loop as long as the value of i is less than or equal to the variable totalreadings. This will make the loop repeat for the correct number of data entries. The final section: i++ tells the computer to add 1 to i each time around the loop. The next requirement of the program is to calculate the mean of the readings. This requires us to make a total of the values entered, then divide by the number of readings. The total can be calculated within the loop. Add the lines of code to calculate and display the mean, using an accuracy of one decimal place: else pnlinput.setvisible(false); pnloutput.setvisible(true); String s=""; s+="readings: \n"; double sum=0; double mean; for (int i=1; i<=totalreadings; i++) s+=" "+ Integer.toString(pollutant[i])+"\n"; sum += pollutant[i]; mean = sum/totalreadings; s+="mean: "+String.format("%.1f",mean)+"\n"; txtoutput.settext(s);

Chapter 5: Loops and arrays 125 Run the program and check that the mean of a series of readings is calculated correctly: The final requirement of the program was to find and display the maximum and minimum of the values. To do this, we can again make use of the loop which checks each of the values in the pollutant[ ] array. Maximum 122 Minimum 122 122 126 115 121 116 reading[1] reading[2] reading[3] reading[4] reading[5] A strategy we can use is to begin be assuming the first array element contains the maximum and minimum value for the data set. The loop then checks each of the array elements in turn: If a higher value is found, this becomes the new maximum. If a lower value is found, this becomes the new minimum. 122 126 115 121 116 reading[1] reading[2] reading[3] reading[4] reading[5] Maximum 122 126 126 Minimum 122 115 115

126 Java Programming for A-level Computer Science Add lines of program code to initialise the maximum and minimum to the first array value, then carry out updates when necessary as the loop checks each array element: s+="readings: \n"; double sum=0; double mean; int max=pollutant[1]; int min=pollutant[1]; for (int i=1; i<=totalreadings; i++) s+=" "+ Integer.toString(pollutant[i])+"\n"; sum += pollutant[i]; if (pollutant[i]>max) max=pollutant[i]; if (pollutant[i]<min) min=pollutant[i]; mean = sum/totalreadings; s+="mean: "+String.format("%.1f",mean)+"\n"; s+="maximum: "+Integer.toString(max)+"\n"; s+="minimum: "+Integer.toString(min)+"\n"; txtoutput.settext(s); Run the program. Enter a set of test data and check that the maximum and minimum values are displayed correctly.

Chapter 5: Loops and arrays 127 In the next program we will again make use of a loop and arrays, this time to produce a railway timetable: A railway service runs along the coast of Cardigan Bay from Machynlleth to Pwllheli. A program is required which will produce a timetable for the journey. The program should input the departure time from Machynlleth, then display the arrival times for other principal stations along the route. Journey times between stations, including stops, are given below: 26 min 27 min 22 min 19 min 24 min Machynlleth Tywyn Barmouth Harlech Porthmadog Pwllheli It will be convenient to store the journey times between stations in an array, so that a loop can be used to generate the timetable. A design for the program is given on the next page. Close all projects, then set up a New Project. Give this the name timetable, and ensure that the Create Main Class option is not selected. Click the Finish button to return to the NetBeans editing page. Right-click on the timetable project, and select New / JFrame Form. Give the Class Name as timetable, and the Package as timetablepackage. Click the Finish button to return to the NetBeans editing screen. 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.

128 Java Programming for A-level Computer Science start set up the journey time array enter departure time: hours enter departure time: minutes display station names in the timetable station = 1 add minutes from the previous station minutes >= 60? Y N minutes = minutes - 60 hours = hours + 1 hours = 24? Y N hours = 0 station = station + 1 Y another station? N stop

Chapter 5: Loops and arrays 129 It will be helpful to users to see the route map for the journey, so we will display this as a picture image. Go to the Projects window and use the + icons to open the timetable project folders until you reach timetablepackage. Right-click on timetablepackage and select New / Java Package. Set the Package Name to timetablepackage.resources: Before continuing, obtain or create a route map similar to the one shown above in the program specification. Use a graphics application such as Photoshop or Paint to set the width of the image to approximately 400 pixels. Go to the NetBeans Design screen, and drag and drop a label component on the form. Locate the icon property, and click the ellipsis (" ") symbol to open the image selection window. Use the Import to Project button to upload the route map. Ensure that the name of this image appears as the File selected and click the OK button.

130 Java Programming for A-level Computer Science The image should appear on the form. Delete the caption for the label. Add further labels 'Departure time from Machynlleth', 'Hours' and 'Minutes', along with two text fields for entering the departure hours and minutes from the first station, Machynlleth. Rename the text fields as txthours and txtminutes. Also add a button with the caption "show timetable". Rename the button as btntimetable: Run the program and check that the form is displayed correctly. Close the program window and return to the NetBeans editing screen. To display the timetable, it will be convenient to use a table component. Locate Table in the palette, and drag and drop this below the 'show timetable' button. Right-click on the table and rename this as tbltraintimes: To set up the correct columns for the table, we will edit the model property. Click on [TableModel] to open an editing window.

Chapter 5: Loops and arrays 131 At the bottom of the editing window, set the number of Rows to 6, and the number of Columns to 3. You should now specify the data for the table: The first column will display the names of the stations along the route, so contains String data. A heading is not needed. The second column contains the hours value of the train time. This will be an integer whole number. A heading "Hours" should be displayed above this column. The third column contains the minutes value of the train time. This will again be an integer. A heading "Mins" should be displayed: Click the OK button to return to the editing screen. The table should now have the correct numbers of columns and rows, and should display headings for the hours and minutes columns:

132 Java Programming for A-level Computer Science Click the Source tab to open the program code window. We will now set up the list of stations in the table, and create an array holding the journey times between station stops. At the start of the timetable class, we will add definitions for the journey array, and integer variables to hold the departure time in hours and minutes for the journey. We go next to the timetable( ) method. This is the first method to run when the program is launched, so it is a good place to initialise the properties or variables which will be needed later in the program. The first block of lines, such as: tbltraintimes.getmodel().setvalueat("barmouth",2,0); will put the names of the stations into the table. The columns and rows are numbered, beginning at zero in the top left corner of the table. The station name 'Barmouth' will be displayed on row 2, in column 0. The second block of lines such as: journey[1]=26; will load the journey times into the correct elements of the journey array. In this case, the journey time for the first leg of the journey, from Machynlleth to Tywyn, is being set to 26 minutes. package timetablepackage; import javax.swing.joptionpane; public class timetable extends javax.swing.jframe int[] journey=new int[6]; int starthours, startminutes; public timetable() initcomponents(); tbltraintimes.getmodel().setvalueat("machynlleth",0,0); tbltraintimes.getmodel().setvalueat("tywyn",1,0); tbltraintimes.getmodel().setvalueat("barmouth",2,0); tbltraintimes.getmodel().setvalueat("harlech",3,0); tbltraintimes.getmodel().setvalueat("porthmadog",4,0); tbltraintimes.getmodel().setvalueat("pwllheli",5,0); journey[1]=26; journey[2]=27; journey[3]=22; journey[4]=19; journey[5]=24; Run the program and check that the station names are displayed correctly in the table:

Chapter 5: Loops and arrays 133 Close the program window to return to the NetBeans editing screen. Click the Design tab to move to the form layout view. Double click the "show timetable" button to create a method. The first stage in producing the timetable is to obtain the departure time of the train service entered by the user. Add lines of program code to read the hour and minute values from the text fields. If either of the text fields has been left blank, then the corresponding variable will be set to zero. We should also allow for an incorrect entry, so a TRY CATCH block has been set up to display an error message box: private void btntimetableactionperformed(java.awt.event.actionevent evt) String s; int hours, minutes; try if (txtminutes.gettext().equals("")) startminutes=0; else s= txtminutes.gettext(); startminutes= Integer.parseInt(s); if (txthours.gettext().equals("")) starthours=0; else s= txthours.gettext(); starthours= Integer.parseInt(s); catch(numberformatexception e) JOptionPane.showMessageDialog(timetable.this,"Incorrect number format"); Run the program. Enter correct values for departure hours and minutes, and check that these are accepted by the program. If a value is entered in an incorrect format, an error message should be displayed when the 'show timetable' button is clicked:

134 Java Programming for A-level Computer Science Close the program and return to the NetBeans editing screen. We will add program code to the button click method. We will begin by carrying out range checks on the departure hours and minutes with the lines: if (hours>=0 && hours<=23)... if (minutes>=0 && minutes<=59)... The timetable should not be displayed if either of these values is outside the allowed range. If the hour and minute entries are valid, the program displays the departure time from the first station, Machynlleth, on the top line of the table tbltraintimes.getmodel().setvalueat(hours,0,1); tbltraintimes.getmodel().setvalueat(minutes,0,2); if (txthours.gettext().equals("")) starthours=0; else s= txthours.gettext(); starthours= Integer.parseInt(s); hours=starthours; minutes=startminutes; if (hours>=0 && hours<=23) if (minutes>=0 && minutes<=59) tbltraintimes.getmodel().setvalueat(hours,0,1); tbltraintimes.getmodel().setvalueat(minutes,0,2); Run the program. Check that valid departure times are accepted by the program and displayed in the table, but hour or minute values which are out of range are not displayed: Close the program and return to the button click method on the source code screen.

Chapter 5: Loops and arrays 135 We will now add a loop which operates five times to display the times for the remaining five stations. Each time around the loop, the program collects the journey time from the corresponding array element. This is added to the current minute value. If the minute total now exceeds 59, the hour must be increased by one, and sixty minutes removed from the current minute total. For example: if a train departs at 9 hours 50 minutes, a journey time of 26 minutes will take the minute total to 76 minutes, but the time should actually become 10 hours 16 minutes: if (hours>=0 && hours<=23) if (minutes>=0 && minutes<=59) tbltraintimes.getmodel().setvalueat(hours,0,1); tbltraintimes.getmodel().setvalueat(minutes,0,2); for (int i=1; i<=5; i++) minutes += journey[i]; if (minutes>59) minutes -=60; hours ++; tbltraintimes.getmodel().setvalueat(hours,i,1); tbltraintimes.getmodel().setvalueat(minutes,i,2); Notice the structure of the loop control line: for ( int i = 1; i <= 5; i++) This has three parts, separated by semi-colons. The first part: int i = 1; defines a local variable i which will be used as a counter while the loop is repeating. We are giving this variable an initial value of 1. The next part: i <= 5; tells the computer to keep repeating the loop as long as the value of i is less than or equal to 5. After that, the loop will end. The final section: i++ tells the computer to add 1 to i each time around the loop. You will see in other programs that loop control structures in Java are very flexible. For example: for ( int year = 1990; year <= 2050; year = year + 10) would create year values from 1990 to 2050, increasing in steps of 10 years each time around the loop.

136 Java Programming for A-level Computer Science Run the program. Enter a variety of departure times and check that the correct times are displayed in the table for each of the stations. The hour should be incremented correctly where necessary during the journey. You may discover that one small problem still remains: if a train departs shortly before midnight, arrival times after midnight will show an incorrect hour. Close the program and return to the button click method. We will add lines of code to correct the hour value if this exceeds 23: for (int i=1; i<=5; i++) minutes += journey[i]; if (minutes>59) minutes -=60; hours ++; if (hours>23) hours =0; tbltraintimes.getmodel().setvalueat(hours,i,1); tbltraintimes.getmodel().setvalueat(minutes,i,2); Run the completed program and check that journeys extending over midnight are timetabled correctly:

Chapter 5: Loops and arrays 137 The next program again involves the input and processing of data using arrays and loops: A bus company carries out a survey of the bus services departing from a town centre. The objective is to compare the numbers of passengers travelling at different times of the day, and to identify heavily used services. A program is required to analyse the data collected. The program should input the number of buses surveyed then for each bus: the departure time - hours the departure time - minutes the service number the number of passengers The program should output: the average numbers of passengers travelling during each part of the day: Morning before 12:00 noon Afternoon 12:00 noon 5:00pm Evening after 5:00pm a list all services with over 30 passengers, giving the departure time and service number. From the specification, we can see that four pieces of information need to be entered for each bus, two integer numbers for the departure time in hours and minutes, a string for the service number (which could possibly include a letter, such as 38B), and an integer to record the number of passengers. A convenient way to store this data will be in four parallel arrays: 9 11 13 16 hours[1] hours [2] hours [3] hours [4]... 20 15 45 0 mins[1] mins [2] mins [3] mins [4]... 38 S16 24X 38 service[1] service[2] service[3] service[4]... 38 26 19 35 pass[1] pass[2] pass[3] pass[4]... Array elements with the same index number refer to the same event. For example, the elements with the index value of 2 show service S16 departing at 11:15 had 26 passengers. A design for the program is given on the next pages.

138 Java Programming for A-level Computer Science start enter number of buses surveyed count = 1 enter departure time hours[count], mins[count] enter service[count] count = count + 1 enter passengers[count] Y another bus? N count = 1 initialise bus counts and passenger totals to zero count = count + 1 time < 12:00? N Y add 1 to morning bus count Y time > 17:00? add passengers[count] to morning passenger total add 1 to evening bus count add passengers[count] to evening passenger total N add 1 to afternoon bus count add passengers[count] to afternoon passenger total Y another bus? N A

Chapter 5: Loops and arrays 139 A morning mean = morning passenger total / morning bus count afternoon mean = afternoon passenger total / afternoon bus count evening mean = evening passenger total / evening bus count display morning, afternoon and evening means count = 1 passengers[count] > 30? Y N output time count = count + 1 output service number Y another bus? N stop Close all projects, then set up a New Project. Give this the name bussurvey, and ensure that the Create Main Class option is not selected. Click Finish to return to the NetBeans editing screen. Right-click on the bussurvey project, and select New / JFrame Form. Give the Class Name as bussurvey,and the Package as bussurveypackage. Click Finish to return to the NetBeans editing screen.

140 Java Programming for A-level Computer Science 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. We will begin by setting up the arrays needed to store the survey data. Click the Source tab to open the program code page, then add the arrays and a buscount variable near the start of the program. public class bussurvey extends javax.swing.jframe int[] hours=new int[100]; int[] mins=new int[100]; String[] service=new String[100]; int[] passengers=new int[100]; int buscount; public bussurvey() initcomponents(); Return to the Design screen. Add a Panel component to the form, and set the border property to BevelBorder. Rename the panel as pnlbuscount. Right-click on the panel and select Layout / Absolute Layout. Add a Label and Spinner component to the panel. Set the text of the label to "Number of buses surveyed", and rename the spinner as spinbuscount. Widen the spinner to allow for multiple digits. When the user has specified the number of buses surveyed, the input of survey results can begin.

Chapter 5: Loops and arrays 141 In previous programs we have entered data by means of text boxes, but there would be advantages in this case if a table similar to a spreadsheet was provided for data entry. This will allow the user to easily check the entries and correct any errors before the data is analysed. Add another panel to the form, renaming this as pnltable. Set the border property to BevelBorder. Drag and drop a Table component on the panel, renaming the table as tblbuses. Locate the model property for the table, and click in the right hand column to open the editing window. Set the numbers of rows and columns to 4. Add titles and data types for each of the columns: Depart hour Integer Depart min Integer Service no String Passengers Integer

142 Java Programming for A-level Computer Science Click the OK button to return to the design screen. Check that the column headings are displayed correctly in the table. Add a button with the caption "OK" to the upper panel. Rename the button as btnok: Go to the Source code page. Add a line of code to the bussurvey method to make the panel containing the table not visible when the program first runs: String[] service=new String[100]; int[] passengers=new int[100]; int buscount; public bussurvey() initcomponents(); pnltable.setvisible(false); Return to the Design screen to display the form, then double click the "OK" button to create a method. The user will click this button after entering the number of buses in the survey. It is then necessary to make the input table visible, and set up a corresponding number of blank rows for entering the survey results. To do this, we must access the model property of the table. Enter lines of program code to carry out these tasks: private void btnokactionperformed(java.awt.event.actionevent evt) pnltable.setvisible(true); DefaultTableModel model = (DefaultTableModel) tblbuses.getmodel(); buscount=(integer) spinbuscount.getvalue(); model.setrowcount(buscount); tblbuses.setmodel(model);

Chapter 5: Loops and arrays 143 Before going further with the programming, scroll to the top of the program listing and add three code modules which will be needed when the program runs. These will allow us to input data into the table, and display of an error message box if necessary: package bussurveypackage; import javax.swing.joptionpane; import javax.swing.table.defaulttablemodel; import javax.swing.table.tablecelleditor; public class bussurvey extends javax.swing.jframe Run the program. Enter different numbers of buses, using the spin component, and check that the correct numbers of blank lines are created in the table. Enter some data into the table. You may notice that the table component has its own error checking procedure. If a value is entered in an incorrect format, for example: entering a letter in the Passengers column, then a red outline will appear around the grid cell. It will not be possible to enter further values until the error is corrected. Close the program and return to the editing screen. Click the Design tab to move to the form layout view.

144 Java Programming for A-level Computer Science Add another panel below the table, renaming this as pnlresults. Place a text area on the panel, with the name txtresults. Complete the form design by adding a button to the table panel with the caption "Analyse data". Rename the button as btnresults. Double click the "Analyse data" to create a method. We will begin by collecting the input data from the table using a loop structure, and storing the values in the parallel arrays. The loop can be enclosed in a TRY CATCH structure to give an error message if data values are missing. private void btnresultsactionperformed(java.awt.event.actionevent evt) pnlresults.setvisible(true); try for (int i=0;i<buscount; i++) hours[i]= (Integer) tblbuses.getmodel().getvalueat(i,0); mins[i]= (Integer) tblbuses.getmodel().getvalueat(i,1); service[i]= (String) tblbuses.getmodel().getvalueat(i,2); passengers[i]= (Integer) tblbuses.getmodel().getvalueat(i,3); catch(nullpointerexception e2) JOptionPane.showMessageDialog(busSurvey.this, "Not all required data entered");

Chapter 5: Loops and arrays 145 Run the program and test the data entry. You may discover that the program does not behave as expected. If a set of data is entered correctly, the "missing data" error message may still appear. This is because data items are not recorded by the table until the user presses the Enter key or clicks on another grid cell. We can attend to this problem now. Close the program window and return to the source code page. Add lines of program code which will force the table to stop editing and accept the current cell value when the "Analyse data" button is clicked. private void btnresultsactionperformed(java.awt.event.actionevent evt) TableCellEditor editor = tblbuses.getcelleditor(); if (editor!= null) editor.stopcellediting(); pnlresults.setvisible(true); try for (int i=0;i<buscount; i++) hours[i]= (Integer) tblbuses.getmodel().getvalueat(i,0); Run the program and check that the table input now works correctly. Close the program window and return to the source code page. A requirement for the program is to display the mean number of passengers using the buses at different times of day. We will begin by calculating the mean number of morning passengers per bus.

146 Java Programming for A-level Computer Science We initialise the numbers of morning buses and passengers to zero. A loop is then used to check each bus in turn. If the departure time is before 12:00 noon, the number of morning buses is increased by one, and the number of passengers is added to the morning passenger total. When the loop ends, the mean is calculated and displayed in the text area: try for (int i=0;i<buscount; i++) hours[i]= (Integer) tblbuses.getmodel().getvalueat(i,0); mins[i]= (Integer) tblbuses.getmodel().getvalueat(i,1); service[i]= (String) tblbuses.getmodel().getvalueat(i,2); passengers[i]= (Integer) tblbuses.getmodel().getvalueat(i,3); double morningpassengers=0; double morningbuses=0; double morningmean=0; for (int i=0;i<buscount; i++) if (hours[i]<12) morningbuses++; morningpassengers += passengers[i]; if (morningbuses>0) morningmean = morningpassengers/morningbuses; else morningmean = 0; String s=""; s+="average passengers: \n"; s+= "Morning "+String.format("%.1f",morningMean)+"\n"; txtresults.settext(s); catch(nullpointerexception e) Run the program. Add some morning bus services and click the button to analyse the data. Check that the average number of passengers for each morning bus is shown correctly:

Chapter 5: Loops and arrays 147 Close the program and return to the source code page. Add similar lines of code to calculate the mean numbers of passengers for afternoon and evening services: double morningpassengers=0; double morningbuses=0; double morningmean=0; double afternoonpassengers=0; double afternoonbuses=0; double afternoonmean=0; double eveningpassengers=0; double eveningbuses=0; double eveningmean=0; for (int i=0;i<buscount; i++) if (hours[i]<12) morningbuses++; morningpassengers += passengers[i]; else if (hours[i]>=17 ) eveningbuses++; eveningpassengers += passengers[i]; else afternoonbuses++; afternoonpassengers += passengers[i]; if (morningbuses>0) morningmean = morningpassengers/morningbuses; else morningmean = 0; if (afternoonbuses>0) afternoonmean = afternoonpassengers/afternoonbuses; else afternoonmean = 0;

148 Java Programming for A-level Computer Science if (eveningbuses>0) eveningmean = eveningpassengers/eveningbuses; else eveningmean = 0; String s=""; s+="average passengers: \n"; s+= "Morning "+String.format("%.1f",morningMean)+"\n"; s+= "Afternoon s+= "Evening "+String.format("%.1f",afternoonMean)+"\n"; "+String.format("%.1f",eveningMean)+"\n"; txtresults.settext(s); catch(nullpointerexception e) Run the program. Enter buses for various times during the day and check that the mean numbers of passengers are displayed correctly:

Chapter 5: Loops and arrays 149 Close the program and return to the source code page. The final program requirement is to list all bus services with more than 30 passengers. Do this by adding another loop to the button click method. When buses with over 30 passengers are found, the program collects the hour and minute values then assembles these into a time format, separated by a colon. If a single digit number is found for the hour or minute value, then a zero is added to produce a standard format. For example: 9 hours 5 minutes is displayed as 09:05. s+="average passengers: \n"; s+= "Morning "+String.format("%.1f",morningMean)+"\n"; s+= "Afternoon "+String.format("%.1f",afternoonMean)+"\n"; s+= "Evening "+String.format("%.1f",eveningMean)+"\n"; s+= "\nservices with over 30 passengers: \n"; int t; String time; for (int i=0;i<buscount; i++) if (passengers[i]>30) t=hours[i]; time=integer.tostring(t); if (t<10) s += "0"; s+= time+":"; t=mins[i]; time=integer.tostring(t); if (t<10) s += "0"; s+= time+" service: "+service[i]; s += "\n"; txtresults.settext(s); catch(nullpointerexception e) Run the program. Enter a set of test data and check that all bus services with more than 30 passengers are listed.