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

Similar documents
Arrays OBJECTIVES. In this chapter you will learn:

Arrays OBJECTIVES. In this chapter you will learn:

Control Statements: Part 1

Introduction to Java Applications

Introduction to Classes and Objects

COMP 110 Programming Exercise: Simulation of the Game of Craps

Introduction to Classes and Objects

Instructor: Eng.Omar Al-Nahal

Methods: A Deeper Look

C Functions. 5.2 Program Modules in C

Methods: A Deeper Look Pearson Education, Inc. All rights reserved.

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Object Oriented Programming. Java-Lecture 6 - Arrays

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

EAS230: Programming for Engineers Lab 1 Fall 2004

Function Call Stack and Activation Records

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

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Functions and Recursion

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

RANDOM NUMBER GAME PROJECT

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

CSE123. Program Design and Modular Programming Functions 1-1

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

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

2.8. Decision Making: Equality and Relational Operators

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Programming with Java

Midterm Examination (MTA)

Introduction to the Java Basics: Control Flow Statements

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

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

JAVASCRIPT LESSON 4: FUNCTIONS

Q5. What values are stored in the array at the comment in main? Note that the incrementall returns void, but does take an int[] parameter.

Final Exam. COMP Summer I June 26, points

Fundamentals of Programming Session 25

Lecture 04 FUNCTIONS AND ARRAYS

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.

STUDENT LESSON A14 Boolean Algebra and Loop Boundaries

Introduction to Java Applications

Introduction to Computer Science Unit 4B. Programs: Classes and Objects

Introduction to Java Programs for Packet #4: Classes and Objects

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

download instant at

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Assignment 2.4: Loops

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

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Introduction to Java & Fundamental Data Types

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

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

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

APCS Semester #1 Final Exam Practice Problems

Chapter 9 Introduction to Arrays. Fundamentals of Java

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

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

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Manipulating One-dimensional Arrays

Introduction to Programming Using Java (98-388)

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

Introduction to Software Development (ISD) Week 3

Programming Assignment #4 Arrays and Pointers

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

Chapter Goals. Contents LOOPS

Introduction to Computer Science Unit 3. Programs

Repetition CSC 121 Fall 2014 Howard Rosenthal

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

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

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

6.5 Function Prototypes and Argument Coercion

CS111: PROGRAMMING LANGUAGE II

Full file at

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

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

CS111: PROGRAMMING LANGUAGE II

Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

Computer Science is...

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

University of Massachusetts Amherst, Electrical and Computer Engineering

Object-Oriented Programming

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Chapter 3 - Functions

Comp 170 Test 1 SAMPLE June 8, 2000

LAB: WHILE LOOPS IN C++

Repetition, Looping. While Loop

More non-primitive types Lesson 06

Chapter 6 - Methods Prentice Hall. All rights reserved.

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

Java Coding 3. Over & over again!

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Final Exam Practice. Partial credit will be awarded.

Chapter 3 Lab Decision Structures

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

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.

Chapter 7 Arrays 3 Assignment Checklist Date: Section: Exercises Assigned: Circle assignments Date Due Prelab Activities Matching YES NO Fill in the Blank 13, 14, 15, 16, 17, 18, 19, 20, 21 Short Answer 22, 23, 24, 25, 26 Programming Output 27, 28, 29, 30, 31, 32 Correct the Code 33, 34, 35, 36, 37, 38 Lab Exercises Exercise 1 Duplicate Elimination YES NO Follow-Up Questions and Activities 1, 2, 3 Exercise 2 Craps Game YES NO Debugging YES NO Labs Provided by Instructor 1. 2. 3. Postlab Activities Coding Exercises 1, 2, 3, 4, 5, 6 Programming Challenges 1, 2

Chapter 7 Arrays 5 Prelab Activities Matching Date: Section: After reading Chapter 7 of Java How to Program: Sixth Edition, answer the given questions. The questions are intended to test and reinforce your understanding of key concepts. You may answer the questions before or during the lab. For each term in the left column, write the letter for the description from the right column that best matches the term. Term 1. pass by value 2. a[ i ][ j ] 3. index 4. new int[ 12 ] 5.... 6. pass by reference 7. array 8. enhanced for statement 9. int c[] 10. tables of values 11. length 12. command-line arguments Description a) Indicates that a method receives a variable number of arguments. b) Declares an array of type int. c) A collection of variables that contain values of the same type. d) Iterates through an array without using a counter. e) Information passed to an application when it executes. f) A copy of the argument s value is made and passed to the called method. g) Represented by an array with two dimensions. h) A calling method gives a called method the ability to access and potentially modify the caller s data directly. i) One element of an array with two dimensions. j) Specifies a particular element in an array. k) Creates an array of integers. l) An array member that contains the number of elements in an array.

Chapter 7 Arrays 7 Prelab Activities Fill in the Blank Fill in the Blank Date: Section: Fill in the blanks for each of the following statements: 13. Every array has a(n) member that specifies the number of elements in the array. 14. When an argument is, a copy of the argument s value is made and passed to the called method. 15. To pass an array to a method, you must specify the of the array as an argument in the method call. 16. An array may be an integer or an integer expression. 17. The first element in every array has index. 18. A(n) argument list is treated as an array within the method declaration s body. 19. Arrays are entities they remain the same length once they are created. 20. must be initialized before they are used and cannot be modified thereafter. 21. To pass one row of a two-dimensional array to a method that receives a one-dimensional array, you specify the array s followed by only the.

Chapter 7 Arrays 9 Prelab Activities Short Answer Short Answer Date: Section: Answer the following questions in the space provided. Your answers should be as concise as possible; aim for two or three sentences. 22. What is an off-by-one error? 23. What benefits does the enhanced for statement provide for array processing? What are its limitations? 24. Why are command-line arguments passed to the main method as Strings? What problems would arise if command-line arguments were passed using an array of doubles?

10 Arrays Chapter 7 Prelab Activities Short Answer 25. Describe how two-dimensional arrays represent a table of data. 26. Differentiate between pass-by-value and pass-by-reference.

Chapter 7 Arrays 11 Prelab Activities Programming Output Programming Output Date: Section: For each of the given program segments, read the code, and write the output in the space provided below each program. [ Note: Do not execute these programs on a computer.] Unless specified otherwise, for the following questions assume that the code segments are contained within the main method of a Java application. 27. What is the output of the following code segment? 1 int array[] = { 8, 6, 9, 7, 6, 4, 4, 5, 8, 10 }; 2 System.out.println( "Index Value" ); 3 4 for ( int i = 0 ; i < array.length; i++ ) 5 System.out.printf( "%d %d\n", i, array[ i ] ); Your answer: 28. What is the output of the following code segment? 1 char sentence[] = { 'H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u' }; 2 String output = " The sentence is: "; 3 4 for ( int i = 0 ; i < sentence.length; i++ ) 5 System.out.printf( "%c ", sentence[ i ] ); 6 7 System.out.println(); Your answer:

12 Arrays Chapter 7 Prelab Activities Programming Output 29. What is the output of the following code segment? 1 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 2 3 for ( int i = 0 ; i < array.length; i++ ) 4 { 5 for ( int j = 0 ; j < array [ i ]; j++ ) 6 System.out.print( "*" ); 7 8 System.out.println(); 9 } Your answer: 30. What is the output of the following code segment? 1 int array[] = { 3, 2, 5 }; 2 3 for ( int i = 0 ; i < 3 ; i++ ) 4 array[ i ] *= 2 ; 5 6 for ( int j : array ) 7 System.out.print( "%d ", j ); 8 9 System.out.println(); Your answer:

Chapter 7 Arrays 13 Prelab Activities Programming Output Given the following declaration of a method 1 public int method1( int... values ) 2 { 3 int mystery = 1 ; 4 5 for ( int i : values ) 6 mystery *= i; 7 8 return mystery; 9 } 31. What is the output of the following code segment? 1 System.out.println( method1( 1, 2, 3, 4, 5 ) ); Your answer: Given the following declaration of a method 1 public int method1( int values[][] ) 2 { 3 int mystery = 1 ; 4 5 for ( int i[] : values ) 6 for ( int j : i ) 7 mystery *= j; 8 9 return mystery; 10 } 32. What is the output of the following code segment? 1 int array[][] = { { 3, 2, 5 }, { 2, 2, 4, 5, 6 }, { 1, 1 } }; 2 3 System.out.println( mystery( array ) );

14 Arrays Chapter 7 Prelab Activities Programming Output Your answer:

Chapter 7 Arrays 15 Prelab Activities Correct the Code Correct the Code Date: Section: Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a compilation error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write no error. [ Note: There may be more than one error in each program segment.] 33. The following code segment should assign 8 to the element of integer array with index 10. 1 array( 10 ) = 8 ; Your answer: 34. The for statement that follows should initialize all of array s elements to -1. 1 int array[] = new int [ 10 ]; 2 3 for ( int i = 0 ; i < 9 ; i++ ) 4 array[ i ] = -1; Your answer:

16 Arrays Chapter 7 Prelab Activities Correct the Code 35. Array a should contain all the integers from 0 through 10, inclusive. 1 int a[] = new int [ 10 ]; 2 3 for ( int i = 0 ; i < 10 ; i++ ) 4 a[ i ] = i; Your answer: 36. The following code segment should allocate two arrays containing five and six elements, respectively. 1 final int arraysize = 5 ; 2 3 int a[] = new int [ arraysize ]; 4 5 arraysize = 6 ; 6 7 int b[] = new int [ arraysize ]; Your answer:

Chapter 7 Arrays 17 Prelab Activities Correct the Code 37. The following code segment should initialize a two-dimensional array, then print its values. 1 int a[][] = new int [ 10 ][ 5 ]; 2 3 for ( int i = 0 ; i < a.length; i++ ) 4 for ( int j = 0 ; j < a[ i ].length; j++ ) 5 a[ j ][ i ] = j; 6 7 for ( int i = 0 ; i < a.length; i++ ) 8 { 9 for ( int j = 0 ; j < a[ i ].length; j++ ) 10 System.out.printf( "%d ", a[ j ][ i ] ); 11 12 System.out.println(); 13 } Your answer: 38. The following code segment should assign the value 10 to the array element that corresponds to the third row and the fourth column. 1 int a[] = new int [ 10 ][ 5 ]; 2 3 a[ 2 ][ 3 ] = 10 ; Your answer:

Chapter 7 Arrays 19 Lab Exercises Lab Exercise 1 Duplicate Elimination Date: Section: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into six parts: 1. Lab Objectives 2. Description of Problem 3. Sample Output 4. Program Template (Fig. L 7.1 and Fig. L 7.2) 5. Problem-Solving Tips 6. Follow-Up Questions and Activities The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Then answer the follow-up questions. The source code for the template is available at www.deitel.com and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 7 of Java How to Program: Sixth Edition. In this lab, you will practice: Declaring and initializing arrays. Comparing input to array elements. Preventing array out-of-bounds errors. The follow-up questions and activities will also give you practice: Initializing array sizes during program execution. Generalizing programs. Problem Description Use a one-dimensional array to solve the following problem: Write an application that inputs five numbers, each of which is between 10 and 100, inclusive. As each number is read, display it only if it is not a duplicate of a number already read. Provide for the worst case, in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user inputs each new value.

20 Arrays Chapter 7 Lab Exercises Lab Exercise 1 Duplicate Elimination 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: 41 11 85 26 41 Program Template 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 3 import java.util.scanner; 4 5 public class Unique 6 { 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 14 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 { 24 // 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 34 in the array */ 35 if (!containsnumber ) 36 { 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 21 Lab Exercises Lab Exercise 1 Duplicate Elimination 40 else 41 System.out.printf( "%d has already been entered\n", 42 number ); 43 } // end if 44 else 45 System.out.println( "number must be between 10 and 100" ); 46 47 // print the list of unique values 48 /* Write code to output the contents of the array */ 49 } // 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 4 { 5 public static void main( String args[] ) 6 { 7 Unique application = new Unique(); 8 application.getnumbers(); 9 } // end main 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. 4. If you have any questions as you proceed, ask your lab instructor for assistance. 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. 2. Modify the program in Follow-Up Question 1 to allow the user to enter numbers until the array is full. 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.

Chapter 7 Arrays 23 Lab Exercises Lab Exercise 2 Craps Game Lab Exercise 2 Craps Game Date: Section: This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. The problem is divided into five parts: 1. Lab Objectives 2. Description of Problem 3. Sample Output 4. Program Template (Fig. L 7.3 and Fig. L 7.4) 5. Problem-Solving Tips The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. The source code for the template is available at www.deitel.com and www.prenhall.com/deitel. Lab Objectives This lab was designed to reinforce programming concepts from Chapter 7 of Java How to Program: Sixth Edition. In this lab you will practice: Declaring and initializing arrays. Using arrays to store sets of data. Problem Description Write an application that runs 1000 games of craps and answers the following questions: a) How many games are won on the first roll, second roll,, twentieth roll and after the twentieth roll? b) How many games are lost on the first roll, second roll,, twentieth roll and after the twentieth roll? c) What are the chances of winning at craps? [ Note: You should discover that craps is one of the fairest casino games. What do you suppose this means?] d) What is the average length of a game of craps?

24 Arrays Chapter 7 Lab Exercises Lab Exercise 2 Craps Game Sample Output 224 games won and 99 games lost on roll #1 74 games won and 119 games lost on roll #2 50 games won and 96 games lost on roll #3 33 games won and 54 games lost on roll #4 23 games won and 47 games lost on roll #5 22 games won and 37 games lost on roll #6 18 games won and 13 games lost on roll #7 8 games won and 18 games lost on roll #8 7 games won and 14 games lost on roll #9 5 games won and 6 games lost on roll #10 5 games won and 6 games lost on roll #11 4 games won and 3 games lost on roll #12 1 games won and 3 games lost on roll #13 1 games won and 0 games lost on roll #14 0 games won and 4 games lost on roll #15 1 games won and 0 games lost on roll #16 0 games won and 0 games lost on roll #17 0 games won and 1 games lost on roll #18 0 games won and 0 games lost on roll #19 0 games won and 0 games lost on roll #20 3 games won and 1 games lost on rolls after the 20th roll The chances of winning are 479 / 1000 = 47.90% The average game length is 3.37 rolls. Program Template 1 // Lab 2: Craps.java 2 // Program plays 1000 games of craps and displays winning 3 // and losing statistics. 4 import java.util.random; 5 6 public class Craps 7 { 8 // create random number generator for use in method rolldice 9 private Random randomnumbers = new Random(); 10 11 // enumeration with constants that represent the game status 12 private enum Status { CONTINUE, WON, LOST }; 13 14 /* Declare array to store the number of games won by number of rolls in the game */ 15 /* Declare array to store the number of games lost by number of rolls in the game */ 16 int winsum = 0 ; // total number of wins 17 int losesum = 0 ; // total number of losses 18 19 // plays one game of craps 20 public void play() 21 { 22 int sumofdice = 0 ; // sum of the dice 23 int mypoint = 0 ; // point if no win or loss on first roll 24 Fig. L 7.3 Craps.java. (Part 1 of 3.)

Chapter 7 Arrays 25 Lab Exercises Lab Exercise 2 Craps Game 25 Status gamestatus; // can contain CONTINUE, WON or LOST 26 27 int roll; // number of rolls for the current game 28 29 /* Create the array to store the number of games won */ 30 /* Create the array to store the number of games lost */ 31 32 for ( int i = 1 ; i <= 1000; i++ ) 33 { 34 sumofdice = rolldice(); // first roll of the dice 35 roll = 1 ; 36 37 // determine game status and point based on sumofdice 38 switch ( sumofdice ) 39 { 40 case 7 : // win with 7 on first roll 41 case 11: // win with 11 on first roll 42 gamestatus = Status.WON; 43 break ; 44 case 2 : // lose with 2 on first roll 45 case 3 : // lose with 3 on first roll 46 case 12 : // lose with 12 on first roll 47 gamestatus = Status.LOST; 48 break ; 49 default : // did not win or lose, so remember point 50 gamestatus = Status.CONTINUE; // game is not over 51 mypoint = sumofdice; // store the point 52 break ; // optional for default case at end of switch 53 } // end switch 54 55 // while game is not complete... 56 while ( gamestatus == Status.CONTINUE ) 57 { 58 sumofdice = rolldice(); // roll dice again 59 roll++; 60 61 // determine game status 62 if ( sumofdice == mypoint ) // win by making point 63 gamestatus = Status.WON; 64 else if ( sumofdice == 7 ) // lose by rolling 7 65 gamestatus = Status.LOST; 66 } // end while 67 68 // all roll results after 20th roll placed in last element 69 /* Write an if statement to test whether the number of rolls is greater than 70 21 and, if true, set number of rolls to 21 */ 71 72 // increment number of wins in that roll 73 if ( gamestatus == Status.WON ) 74 { 75 /* Write code to increment the number of games won for a 76 specific number of rolls */ 77 /* Write code to increment the overall number of games won */ 78 } // end if 79 else // increment number of losses in that roll 80 { Fig. L 7.3 Craps.java. (Part 2 of 3.)

26 Arrays Chapter 7 Lab Exercises Lab Exercise 2 Craps Game 81 /* Write code to increment the number of games lost for a 82 specific number of rolls */ 83 /* Write code to increment the overall number of games lost */ 84 } // end else 85 } // end for 86 87 printstats(); 88 } // end method play 89 90 // print win/loss statistics 91 public void printstats() 92 { 93 int totalgames = winsum + losesum; // total number of games 94 int length = 0 ; // total length of the games 95 96 // display number of wins and losses on all rolls 97 for ( int i = 1 ; i <= 21 ; i++ ) 98 { 99 /* Write an if statement to test whether i is equal to 21 */ 100 /* Output number of games won and lost after the 20th roll */ 101 else 102 /* Output number of games won and lost after each roll less than 20 */ 103 104 // calculate total number of rolls to win/lose all games 105 // add number of wins by number of rolls needed to win 106 // add number of losses by number of rolls needed to lose 107 /* Write code to calculate total length of games */ 108 } // end for 109 110 // calculate chances of winning 111 System.out.printf( "\n%s %d / %d = %.2f%%\n", 112 "The chances of winning are", winsum, totalgames, 113 ( 100.0 * winsum / totalgames ) ); 114 115 116 System.out.printf( "The average game length is %.2f rolls.\n", 117 ( ( double ) length / totalgames ) ); 118 } // end method printstats 119 120 // roll dice, calculate sum and display results 121 public int rolldice() 122 { 123 // pick random die values 124 int die1 = 1 + randomnumbers.nextint( 6 ); 125 int die2 = 1 + randomnumbers.nextint( 6 ); 126 int sum = die1 + die2; // sum die values 127 128 return sum; // return sum of dice 129 } // end method rolldice 130 } // end class Craps Fig. L 7.3 Craps.java. (Part 3 of 3.)

Chapter 7 Arrays 27 Lab Exercises Lab Exercise 2 Craps Game 1 // Lab 2: CrapsTest.java 2 // Test application for class Craps 3 public class CrapsTest 4 { 5 public static void main( String args[] ) 6 { 7 Craps game = new Craps(); 8 game.play(); 9 } // end main 10 } // end class CrapsTest Fig. L 7.4 CrapsTest.java Problem-Solving Tips 1. The arrays to hold the number of wins and losses by number of rolls should have 22 elements. We are keeping track of the number of wins and losses decided on the first through twentieth roll along with games decided after the twentieth roll. That requires 21 elements. The extra element is because arrays begin with element zero. This element will not hold any information in the program. 2. To calculate the total number of rolls, multiply each index in the arrays by the value of that element in the array. 3. If you have any questions as you proceed, ask your lab instructor for assistance.

Chapter 7 Arrays 29 Lab Exercises 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 and at www.prenhall.com/deitel. Sample Output Enter sales person number (-1 to end): 1 Enter product number: 4 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): 4 Enter product number: 1 Enter sales amount: 1554 Enter sales person number (-1 to end): -1 Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total 1 0.00 0.00 678.00 1554.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 4 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 1554.00 Broken Code 1 // Debugging Problem Chapter 7: Sales2.java 2 // Program totals sales for salespeople and products. 3 import java.util.scanner; 4 5 public class Sales2 6 { 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 ][ 4 ]; 13 14 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.)

30 Arrays Chapter 7 Lab Exercises 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 24 // 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 34 35 // total for each salesperson 36 double salespersontotal[][] = new double[ 4 ]; 37 38 // display the table 39 for ( int column = 0 ; column < 4 ; column++ ) 40 salespersontotal[ column ][ row ] = 0 ; 41 42 System.out.printf( "%7s%14s%14s%14s%14s%10s\n", 43 "Product", "Salesperson 1", "Salesperson 2", 44 "Salesperson 3", "Salesperson 4", "Total" ); 45 46 // for each column of each row, print the appropriate 47 // value representing a person's sales of a product 48 for ( int row = 0 ; row < 5 ; row++ ) 49 { 50 double producttotal = 0.0 ; 51 System.out.printf( "%7d", ( row + 1 ) ); 52 53 for ( int column = 0 ; column < 4 ; column++ ) { 54 System.out.printf( "%14.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 64 for ( int column = 0 ; column < 4 ; column++ ) 65 System.out.printf( "%14.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 31 Lab Exercises Debugging 1 // Debugging Problem Chapter 7: Sales2Test.java 2 // Test application for class Sales2 3 public class Sales2Test 4 { 5 public static void main( String args[] ) 6 { 7 Sales2 application = new Sales2(); 8 application.calculatesales(); 9 } // end main 10 } // end class Sales2Test Fig. L 7.6 Sales2Test.java

Chapter 7 Arrays 33 Postlab Activities Coding Exercises Date: Section: These coding exercises reinforce the lessons learned in the lab and provide additional programming experience outside the classroom and laboratory environment. They serve as a review after you have successfully completed the Prelab Activities and Lab Exercises. For each of the following problems, write a program or a program segment that performs the specified action. 1. Write a line of code that declares and creates a 100-element array of int s. 2. Initialize all the elements in the array of Coding Exercise 1 to 1. 3. Write a line of code that accesses the seventh element of the array in Coding Exercise 2 and sets its value to 7.

34 Arrays Chapter 7 Postlab Activities Coding Exercises 4. Write a method printarray that displays the contents of the array created in Coding Exercise 1. Assume that the method receives array1 as an argument in a method call. Display the contents of the array with each number separated by a space. In addition, start a new line after every 20 elements. 5. Create a char array and use an array initializer to initialize the array with the characters in the string "Hi there". Display the contents of the array using a for statement. Separate each character in the array with a space. 6. Write a for statement that prints only "Hi" from the array you created in Coding Exercise 5.

Chapter 7 Arrays 35 Postlab Activities Programming Challenges Programming Challenges Date: Section: The Programming Challenges are more involved than the Coding Exercises and may require a significant amount of time to complete. Write a Java program for each of the problems in this section. The answers to these problems are available at www.deitel.com and www.prenhall.com/deitel. Pseudocode, hints or sample outputs are provided for each problem to aid you in your programming. 1. ( Dice Rolling) Write an application to simulate the rolling of two dice. The application should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums. Figure L 7.7 shows the 36 possible combinations of the two dice. Your application should roll the dice 36,000 times. Use a onedimensional array to keep track of the number of times each possible sum appears. Display the results in tabular format. Determine whether the totals are reasonable (e.g., there are six ways to roll a 7, so approximately one-sixth of the rolls should be 7). 1 2 3 4 5 6 1 2 3 4 5 6 7 2 3 4 5 6 7 8 3 4 5 6 7 8 9 4 5 6 7 8 9 10 5 6 7 8 9 10 11 6 7 8 9 10 11 12 Fig. L 7.7 The 36 possible outcomes of rolling two dice. Hints: Keep track of how many times each total (2 through 12) occurs. This total is used to calculate the percentage of the time that each total occurs. Define a loop that iterates 36,000 times. During each iteration, roll the dice, calculate the total and update the count for the particular total in the array. Create an array large enough that you can use the sum of the dice as the index into the array.

36 Arrays Chapter 7 Postlab Activities Programming Challenges Your output should appear as follows: Sum Frequency Percentage 2 1027 2.85 3 2030 5.64 4 2931 8.14 5 3984 11.07 6 5035 13.99 7 5996 16.66 8 4992 13.87 9 4047 11.24 10 2961 8.23 11 1984 5.51 12 1013 2.81 2. (Airline Reservations System) A small airline has just purchased a computer for its new automated reservations system. You have been asked to develop the new system. You are to write an application to assign seats on each flight of the airline s only plane (capacity: 10 seats). Your application should display the following alternatives: Please type 1 for First Class and Please type 2for Economy. If the user types 1, your application should assign a seat in the first-class section (seats 1 5). If the user types 2, your application should assign a seat in the economy section (seats 6 10). Your application should then display a boarding pass indicating the person s seat number and whether it is in the first-class or economy section of the plane. Use a one-dimensional array of primitive type boolean to represent the seating chart of the plane. Initialize all the elements of the array to false to indicate that all the seats are empty. As each seat is assigned, set the corresponding elements of the array to true to indicate that the seat is no longer available. Your application should never assign a seat that has already been assigned. When the economy section is full, your application should ask the person if it is acceptable to be placed in the first-class section (and vice versa). If yes, make the appropriate seat assignment. If no, display the message "Next flight leaves in Hints: 3hours." Use an array of boolean s to represent the seats on the airplane. Use int s to keep track of the next available seat for each of the seat types.

Chapter 7 Arrays 37 Postlab Activities Programming Challenges Your output should appear as follows: Please type 1 for First Class Please type 2 for Economy choice: 1 First Class. Seat #1 Please type 1 for First Class Please type 2 for Economy choice: 2 Economy Class. Seat #6... Please type 1 for First Class Please type 2 for Economy choice: 1 First Class is full, Economy Class? 1. Yes, 2. No. Your choice: 1 Economy Class. Seat #7