Arrays OBJECTIVES. In this chapter you will learn:

Similar documents
Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Arrays OBJECTIVES. In this chapter you will learn:

Control Statements: Part 1

Introduction to Java Applications

Instructor: Eng.Omar Al-Nahal

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Programming with Java

Introduction to Classes and Objects

download instant at

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Repetition CSC 121 Fall 2014 Howard Rosenthal

Assignment 2.4: Loops

CS111: PROGRAMMING LANGUAGE II

2.8. Decision Making: Equality and Relational Operators

Midterm Examination (MTA)

Manipulating One-dimensional Arrays

THE JAVA FOR STATEMENT

1. A company has vans to transport goods from factory to various shops. These vans fall into two categories: 50 items 150 items

COMP 110 Programming Exercise: Simulation of the Game of Craps

AP CS Unit 3: Control Structures Notes

Supplementary Test 1

Object Oriented Programming. Java-Lecture 1

Chapter 3 Lab Decision Structures

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CS111: PROGRAMMING LANGUAGE II

Computer Programming: C++

Introduction to Classes and Objects

Object Oriented Programming. Java-Lecture 6 - Arrays

Introduction to Java & Fundamental Data Types

Task #1 The if Statement, Comparing Strings, and Flags

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 6: Using Arrays

Arrays. Eng. Mohammed Abdualal

1007 Imperative Programming Part II

Section 2.2 Your First Program in Java: Printing a Line of Text

CS141 Programming Assignment #6

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Introduction to Computer Science Unit 2. Exercises

Chapter 4: Control structures. Repetition

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Introduction to Software Development (ISD) Week 3

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

5) (4 points) What is the value of the boolean variable equals after the following statement?

Chapter 4: Control structures

AP Computer Science Unit 1. Programs

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Fundamentals of Programming Data Types & Methods

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

CS141 Programming Assignment #8

Introduction to Computer Science Unit 3. Programs

Elementary Programming

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Simple Java Programming Constructs 4

Introduction to Java Applications

APCS Semester #1 Final Exam Practice Problems

Introduction to Programming Using Java (98-388)

CS 200 Using Objects. Jim Williams, PhD

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

Java Coding 3. Over & over again!

Practice Midterm 1. Problem Points Score TOTAL 50

Welcome to the Using Objects lab!

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Computer Science is...

Top-Down Program Development

CS 101 Spring 2007 Midterm 2 Name: ID:

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Practice Midterm 1 Answer Key

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

Arrays & Classes. Problem Statement and Specifications

Introduction to Computer Science Unit 2. Notes

Example: Monte Carlo Simulation 1

Data dependent execution order data dependent control flow

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Section 2.2 Your First Program in Java: Printing a Line of Text

Welcome to the Using Objects lab!

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

AP CS A Exam Review Answer Section

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Chapter 6 Lab Classes and Objects

Chapter 6 Lab Classes and Objects

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

This class simulates the Sudoku board. Its important methods are setcell, dorow, docolumn and doblock.

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Transcription:

7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis Carroll OBJECTIVES In this chapter you will learn: What arrays are. To use arrays to store data in and retrieve data from lists and tables of values. To declare an array, initialize an array and refer to individual elements of an array. To use the enhanced for statement to iterate through arrays. To pass arrays to methods. To declare and manipulate multidimensional arrays. To write methods that use variable-length argument lists. To read command-line arguments into a program.

282 Arrays Chapter7 Sample Output Enter number: 11 11 Enter number: 85 11 85 Enter number: 26 11 85 26 Enter number: 11 11 has already been entered 11 85 26 Enter number: 1 11 85 26 1 Program Template 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 /* Create an array of five elements*/ 13 int count = 0 ; // number of uniques read 1 int entered = 0 ; // number of entered numbers 15 16 while( entered < numbers.length ) 17 { 18 System.out.print( "Enter number: " ); 19 /* Write code here to retrieve the input from the user */ 20 21 // validate the input 22 /* Write an if statement that validates the input */ 23 { 2 // flags whether this number already exists 25 boolean containsnumber = false; 26 27 // increment number of entered numbers 28 entered++; 29 30 /* Compare the user input to the unique numbers in the array using a for 31 statement. If the number is unique, store new number */ 32 33 /* add the user input to the array only if the number is not already 3 in the array */ 35 if (!containsnumber ) 3 37 /* Write code to add the number to the array and increment 38 unique items input */ 39 } // end if Fig. L 7.1 Unique.java. (Part 1 of 2.)

Chapter 7 Arrays 283 0 else 1 System.out.printf( "%d has already been entered\n", 2 number ); 3 } // end if else 5 System.out.println( "number must be between 10 and 100" ); 6 7 // print the list of unique values 8 /* Write code to output the contents of the array */ 9 } // end while 50 } // end method getnumbers 51 } // end class Unique Fig. L 7.1 Unique.java. (Part 2 of 2.) 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest Fig. L 7.2 UniqueTest.java. Problem-Solving Tips 1. Initialize the integer array numbers to hold five elements. This is the maximum number of values the program must store if all values input are unique. 2. Remember to validate the input and display an error message if the user inputs invalid data. 3. If the number entered is not unique, display a message to the user; otherwise, store the number in the array and display the list of unique numbers entered so far.. If you have any questions as you proceed, ask your lab instructor for assistance. Solution 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int numbers[] = new int[ 5 ]; // list of unique numbers 13 int count = 0 ; // number of uniques read 1 int entered = 0 ; // number of entered numbers 15

28 Arrays Chapter7 16 while( entered < numbers.length ) 17 { 18 System.out.print( "Enter number: " ); 19 int number = input.nextint(); 20 21 // validate the input 22 if ( 10 <= number && number <= 100 ) 23 { 2 // flags whether this number already exists 25 boolean containsnumber = false; 26 27 // increment number of entered numbers 28 entered++; 29 30 // compare input number to unique numbers in array 31 for ( int i = 0 ; i < count; i++ ) 32 // if new number is duplicate, set the flag 33 if ( number == numbers[ i ] ) 3 containsnumber = true; 35 36 // add only if the number is not there already 37 if (!containsnumber ) 38 { 39 numbers[ count ] = number; 0 count++; 1 } // end if 2 else 3 System.out.printf( "%d has already been entered\n", number ); } // end if 5 else 6 System.out.println( "number must be between 10 and 100" ); 7 8 // print the list 9 for ( int i = 0 ; i < count; i++ ) 50 System.out.printf( "%d ", numbers[i] ); 51 52 System.out.println(); 53 } // end while 5 } // end method getnumbers 55 } // end class Unique 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest

Chapter 7 Arrays 285 Follow-Up Questions and Activities 1. Modify the program in Lab Exercise 1 to input 30 numbers, each of which is between 10 to 500, inclusive. 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int numbers[] = new int[ 30 ]; // list of unique numbers 13 int count = 0 ; // number of uniques read 1 int entered = 0 ; // number of entered numbers 15 16 while( entered < numbers.length ) 17 { 18 System.out.print( "Enter number: " ); 19 int number = input.nextint(); 20 21 // validate the input 22 if ( 10 <= number && number <= 500 ) 23 { 2 // flags whether this number already exists 25 boolean containsnumber = false; 26 27 // increment number of entered numbers 28 entered++; 29 30 // compare input number to unique numbers in array 31 for ( int i = 0 ; i < count; i++ ) 32 // if new number is duplicate, set the flag 33 if ( number == numbers[ i ] ) 3 containsnumber = true; 35 36 // add only if the number is not there already 37 if (!containsnumber ) 38 { 39 numbers[ count ] = number; 0 count++; 1 } // end if 2 else 3 System.out.printf( "%d has already been entered\n", number ); 5 } // end if 6 else 7 System.out.println( "number must be between 10 and 100" ); 8 9 // print the list 50 for ( int i = 0 ; i < count; i++ ) 51 System.out.printf( "%d ", numbers[i] ); 52 System.out.println(); 53 } // end while 5 } // end method getnumbers 55 } // end class Unique

286 Arrays Chapter7 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest 2. Modify the program in Follow-Up Question 1 to allow the user to enter numbers until the array is full. 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 int numbers[] = new int[ 30 ]; // list of unique numbers 13 int count = 0 ; // number of uniques read 1 15 while( count < numbers.length ) 1 17 System.out.print( "Enter number: " ); 18 int number = input.nextint(); 19 20 // validate the input 21 if ( 10 <= number && number <= 500 ) 22 { 23 // flags whether this number already exists 2 boolean containsnumber = false; 25 26 // compare input number to unique numbers in array 27 for ( int i = 0 ; i < count; i++ ) 28 // if new number is duplicate, set the flag 29 if ( number == numbers[ i ] ) 30 containsnumber = true; 31 32 // add only if the number is not there already 33 if (!containsnumber ) 3 35 numbers[ count ] = number; 36 count++; 37 } // end if 38 else 39 System.out.printf( "%d has already been entered\n", 0 number ); 1 } // end if 2 else 3 System.out.println( "number must be between 10 and 100" );

Chapter 7 Arrays 287 5 // print the list 6 for ( int i = 0 ; i < count; i++ ) 7 System.out.printf( "%d ", numbers[i] ); 8 System.out.println(); 9 } // end while 50 } // end method getnumbers 51 } // end class Unique 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest 3. Modify your solution to Follow-Up Question 2 to allow the user to enter the size of the array as the application begins execution. 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); 11 12 System.out.print( "How many numbers will you enter? " ); 13 int number = input.nextint(); 1 15 int numbers[] = new int[ number ]; // list of unique numbers 16 int count = 0 ; // number of uniques read 17 18 while( count < numbers.length ) 19 { 20 System.out.print( "Enter number: " ); 21 number = input.nextint(); 22 23 // validate the input 2 if ( 10 <= number && number <= 500 ) 25 { 26 // flags whether this number already exists 27 boolean containsnumber = false; 28

288 Arrays Chapter7 29 // compare input number to unique numbers in array 30 for ( int i = 0 ; i < count; i++ ) 31 // if new number is duplicate, set the flag 32 if ( number == numbers[ i ] ) 33 containsnumber = true; 3 35 // add only if the number is not there already 36 if (!containsnumber ) 37 { 38 numbers[ count ] = number; 39 count++; 0 } // end if 1 else 2 System.out.printf( "%d has already been entered\n", 3 number ); } // end if 5 else 6 System.out.println( "number must be between 10 and 100" ); 7 8 // print the list 9 for ( int i = 0 ; i < count; i++ ) 50 System.out.printf( "%d ", numbers[i] ); 51 System.out.println(); 52 } // end while 53 } // end method getnumbers 5 } // end class Unique 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest

Chapter 7 Arrays 297 Debugging Debugging Date: Section: The program in this section does not run properly. Fix all the compilation errors, so that the program will compile successfully. Once the program compiles, compare the output to the sample output, and eliminate any logic errors that exist. The sample output demonstrates what the program s output should be once the program s code is corrected. The file is available at www.deitel.com/books/jhtp7/ and at www.prenhall.com/deitel. Sample Output Enter sales person number (-1 to end): 1 Enter product number: Enter sales amount: 1082 Enter sales person number (-1 to end): 2 Enter product number: 3 Enter sales amount: 998 Enter sales person number (-1 to end): 3 Enter product number: 1 Enter sales amount: 678 Enter sales person number (-1 to end): Enter product number: 1 Enter sales amount: 155 Enter sales person number (-1 to end): -1 Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson Total 1 0.00 0.00 678.00 155.00 2232.00 2 0.00 0.00 0.00 0.00 0.00 3 0.00 998.00 0.00 0.00 998.00 1082.00 0.00 0.00 0.00 1082.00 5 0.00 0.00 0.00 0.00 0.00 Total 1082.00 998.00 678.00 155.00 Broken Code 1 // Debugging Problem Chapter 7: Sales2.java 2 // Program totals sales for salespeople and products. 5 public class Sales2 7 public void calculatesales() 8 { 9 Scanner input = new Scanner( System.in ); 10 // sales array holds data on number of each product sold 11 // by each salesman 12 double sales = new double[ 5 ][ ]; 13 1 System.out.print( "Enter sales person number (-1 to end): " ); 15 int person = input.nextint(); Fig. L 7.5 Sales2.java. (Part 1 of 2.)

298 Arrays Chapter7 Debugging 16 17 while ( person!= -1 ) 18 { 19 System.out.print( "Enter product number: " ); 20 int product = input.next(); 21 System.out.print( "Enter sales amount: " ); 22 double amount = input.nextdouble(); 23 2 // error-check the input 25 if ( person < 1 && person > 5 && 26 product >= 1 && product < 6 && amount >= 0 ) 27 sales[ product - 1 ][ person - 1 ] += amount; 28 else 29 System.out.println( "Invalid input!" ); 30 31 System.out.print( "Enter sales person number (-1 to end): " ); 32 person = input.nextint(); 33 } // end while 3 35 // total for each salesperson 36 double salespersontotal[][] = new double[ ]; 37 38 // display the table 39 for ( int column = 0 ; column < ; column++ ) 0 salespersontotal[ column ][ row ] = 0 ; 1 2 System.out.printf( "%7s%1s%1s%1s%1s%10s\n", 3 "Product", "Salesperson 1", "Salesperson 2", "Salesperson 3", "Salesperson ", "Total" ); 5 6 // for each column of each row, print the appropriate 7 // value representing a person's sales of a product 8 for ( int row = 0 ; row < 5 ; row++ ) 9 { 50 double producttotal = 0.0; 51 System.out.printf( "%7d", ( row + 1 ) ); 52 53 for ( int column = 0 ; column < ; column++ ) { 5 System.out.printf( "%1.2f", sales[ column ][ row ] ); 55 producttotal += sales[ column ][ row ]; 56 salespersontotal[ column ] += sales[ column ][ row ]; 57 } // end for 58 59 System.out.printf( "%10.2f\n", producttotal ); 60 } // end for 61 62 System.out.printf( "%7s", "Total" ); 63 6 for ( int column = 0 ; column < ; column++ ) 65 System.out.printf( "%1.2f", salespersontotal[ column ] ); 66 67 System.out.println(); 68 } // end method calculatesales 69 } // end class Sales2 Fig. L 7.5 Sales2.java. (Part 2 of 2.)

Chapter 7 Arrays 299 Debugging 1 // Debugging Problem Chapter 7: Sales2Test.java 2 // Test application for class Sales2 3 public class Sales2Test 7 Sales2 application = new Sales2(); 8 application.calculatesales(); 10 } // end class Sales2Test Fig. L 7.6 Sales2Test.java

300 Arrays Chapter7 Debugging Solution 1 // Debugging Problem Chapter 7: Sales2.java 2 // Program totals sales for salespeople and products. 5 public class Sales2 7 public void calculatesales() 8 { 9 Scanner input = new Scanner( System.in ); 10 // sales array holds data on number of each product sold 11 // by each salesman 12 double sales [][] = new double[ 5 ][ ]; 13 1 System.out.print( "Enter sales person number (-1 to end): " ); 15 int person = input.nextint(); 16 17 while ( person!= -1 ) 18 { 19 System.out.print( "Enter product number: " ); 20 int product = input. nextint(); 21 System.out.print( "Enter sales amount: " ); 22 double amount = input.nextdouble(); 23 2 // error-check the input 25 if ( person >= 1 && person < 5 && 26 product >= 1 && product < 6 && amount >= 0 ) 27 sales[ product - 1 ][ person - 1 ] += amount; 28 else 29 System.out.println( "Invalid input!" ); 30 31 System.out.print( "Enter sales person number (-1 to end): " ); 32 person = input.nextint(); 33 } // end while 3 35 // total for each salesperson 36 double salespersontotal[] = new double[ ]; 37 38 // display the table 39 for ( int column = 0 ; column < ; column++ ) 0 salespersontotal[ column ] = 0 ; 1 2 System.out.printf( "%7s%1s%1s%1s%1s%10s\n", 3 "Product", "Salesperson 1", "Salesperson 2", "Salesperson 3", "Salesperson ", "Total" ); 5 6 // for each column of each row, print the appropriate 7 // value representing a person's sales of a product 8 for ( int row = 0 ; row < 5 ; row++ ) 9 { 50 double producttotal = 0.0; 51 System.out.printf( "%7d", ( row + 1 ) ); 52 53 for ( int column = 0 ; column < ; column++ ) { 5 System.out.printf( "%1.2f", sales[ row ][ column ] ); Fig. L 7.7 Sales2.java

Chapter 7 Arrays 301 Debugging 55 producttotal += sales[ row ][ column ]; 56 salespersontotal[ column ] += sales[ row ][ column ]; 57 } // end for 58 59 System.out.printf( "%10.2f\n", producttotal ); 60 } // end for 61 62 System.out.printf( "%7s", "Total" ); 63 6 for ( int column = 0 ; column < ; column++ ) 65 System.out.printf( "%1.2f", salespersontotal[ column ] ); 66 67 System.out.println(); 68 } // end method calculatesales 69 } // end class Sales2 Fig. L 7.7 Sales2.java 1 // Debugging Problem Chapter 7: Sales2Test.java 2 // Test application for class Sales2 3 public class Sales2Test 7 Sales2 application = new Sales2(); 8 application.calculatesales(); 10 } // end class Sales2Test Fig. L 7.8 Sales2Test.java List of Errors Line 12 declaration of two-dimensional array sales is missing the square brackets. Line 20 Use Scanner method nextint to input an integer from the user. Line 25 Tests used to validate value of person have the wrong comparison operators. Line 36 Declaration of array salespersontotal should only have one set of square brackets. Line 0 Array salespersontotal should be indexed only with the value of column. Lines 5 56 Array sales should be indexed with row first, then column.