AhmadLang / Java, How To Program, 2004
.pdf
If it is correct, display the message "Very good!" and ask another multiplication question. If the answer is wrong, display the message "No. Please try again." and let the student try the same question repeatedly until the student finally gets it right. A separate method should be used to generate each new question. This method should be called once when the application begins execution and each time the user answers the question correctly.
6.31The use of computers in education is referred to as computer-assisted instruction (CAI). One problem that develops in CAI environments is student fatigue. This problem can be eliminated by varying the computer's responses to hold the student's attention. Modify the program of Exercise 6.30 so that the various comments are displayed for each correct answer and each incorrect answer as follows:
Responses to a correct answer:
Very good!
Excellent!
Nice work!
Keep up the good work!
Responses to an incorrect answer:
No. Please try again.
Wrong. Try once more.
Don't give up!
No. Keep trying.
Use random-number generation to choose a number from 1 to 4 that will be used to select an appropriate response to each answer. Use a switch statement to issue the responses.
6.32More sophisticated computer-assisted instruction systems monitor the student's performance over a period of time. The decision to begin a new topic is often based on the student's success with previous topics. Modify the program of Exercise 6.31 to count the number of correct and incorrect responses typed by the student. After the student types 10 answers, your program should calculate the percentage of correct responses. If the percentage is lower than 75%, display Please ask your instructor for extra help and reset the program so another student can try it.
6.33Write an application that plays "guess the number" as follows: Your program chooses the number to be guessed by selecting a random integer in the range 1 to 1000. The application displays the prompt Guess a number between 1 and 1000. The player inputs a first guess. If the player's guess is incorrect, your program should display Too high. Try again. or Too low. Try again. to help the player "zero in" on the correct answer. The program should prompt the user for the next guess. When the user enters the correct answer, display Congratulations. You guessed the number!, and allow the user to choose whether to play again. [Note : The guessing technique employed in this problem is similar to a binary search, which is discussed in Chapter 16, Searching and Sorting.]
6.34Modify the program of Exercise 6.33 to count the number of guesses the player makes. If the number is 10 or fewer, display Either you know the secret or you got lucky! If the player guesses the number in 10 tries, display Aha! You know the secret! If the player makes more than 10 guesses, display You should be able to do better! Why should it take no more than 10 guesses? Well, with each "good guess," the player should be able to eliminate half of the numbers. Now show why any number from 1 to 1000 can be guessed in 10 or fewer tries.
[Page 284]
6.35Exercise 6.30 through Exercise 6.32 developed a computer-assisted instruction program to teach an elementary school student multiplication. Perform the following enhancements:
a.Modify the program to allow the user to enter a school grade-level capability. A grade level of 1 means that the program should use only single-digit numbers in the problems, a grade level of 2 means that the program should use numbers as large as two digits, and so on.
b.Modify the program to allow the user to pick the type of arithmetic problems
he or she wishes to study. An option of 1 means addition problems only, 2 means subtraction problems only, 3 means multiplication problems only, 4 means division problems only and 5 means a random mixture of problems of all these types.
6.36Write method distance to calculate the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double. Incorporate this method into an application that enables the user to enter the coordinates of the points.
6.37Modify the craps program of Fig. 6.9 to allow wagering. Initialize variable bankBalance to 1000 dollars. Prompt the player to enter a wager. Check that wager is less than or equal to bankBalance, and if it is not, have the user reenter wager until a valid wager is entered. After a correct wager is entered, run one game of craps. If the player
wins, increase bankBalance by wager and display the new bankBalance. If the player loses, decrease bankBalance by wager, display the new bankBalance, check whether bankBalance has become zero and, if so, display the message "Sorry. You busted!" As the game progresses, display various messages to create some "chatter," such as
"Oh, you're going for broke, huh?" or "Aw c'mon, take a chance!" or "You're up big. Now's the time to cash in your chips!". Implement the "chatter" as a separate method that randomly chooses the string to display.
6.38Write an application that displays a table of the binary, octal, and hexadecimal equivalents of the decimal numbers in the range 1 through 256. If you are not familiar with these number systems, read Appendix E first.
[Page 285]
Chapter 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.
[Page 286]
Outline
7.1 Introduction
7.2 Arrays
7.3 Declaring and Creating Arrays
7.4 Examples Using Arrays
7.5 Case Study: Card Shuffling and Dealing Simulation
7.6 Enhanced for Statement
7.7 Passing Arrays to Methods
7.8 Case Study: Class GradeBook Using an Array to Store Grades
7.9 Multidimensional Arrays
7.10 Case Study: Class GradeBook Using a Two-Dimensional Array
7.11 Variable-Length Argument Lists
7.12 Using Command-Line Arguments
7.13 (Optional) GUI and Graphics Case Study: Drawing Arcs
7.14 (Optional) Software Engineering Case Study: Collaboration Among Objects
7.15 Wrap-Up
Summary
Terminology
Self-Review Exercises
Answers to Self-Review Exercises
Exercises
Special Section: Building Your Own Computer
[Page 286 (continued)]
7.1. Introduction
This chapter introduces the important topic of data structurescollections of related data items. Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entitiesthey remain the same length once they are created, although an array variable may be reassigned such that it refers to a new array of a different length.
After discussing how arrays are declared, created and initialized, this chapter presents a series of practical examples that demonstrate several common array manipulations. We also present a case study that examines how arrays can help simulate the shuffling and dealing of playing cards for use in an application that implements a card game. The chapter then introduces Java's enhanced for statement, which allows a program to access the data in an array more easily than the counter-controlled for statement presented in Section 5.3 does. Two sections of the chapter enhance the case study of class GradeBook in Chapters 35. In particular, we use arrays to enable the class to maintain a set of grades in memory and analyze student grades from multiple exams in a semestertwo capabilities that were absent from previous versions of the class. These and other chapter examples demonstrate the ways in which arrays allow programmers to organize and manipulate data.
[Page 286 (continued)]
7.2. Arrays
An array is a group of variables (called elements or components) containing values that all have the same type. Recall that types are divided into two categoriesprimitive types and reference types. Arrays are objects, so they are considered reference types. As you will soon see, what we typically think of as an array is actually a reference to an array object in memory. The elements of an array can be either primitive types or reference types (including arrays, as we will see in Section 7.9). To refer to a particular element in an array, we specify the name of the reference to the array and the position number of the element in the array. The position number of the element is called the element's index or subscript.
[Page 287]
Figure 7.1 shows a logical representation of an integer array called c. This array contains 12 elements. A program refers to any one of these elements with an array-access expression that includes the name of the array followed by the index of the particular element in square brackets ([]). The first element in every array has index zero and is sometimes called the zeroth element. Thus, the elements of array c are c[ 0 ], c[ 1 ], c[ 2 ] and so on. The highest index in array c is 11, which is 1 less than 12the number of elements in the array. Array names follow the same conventions as other variable names.
Figure 7.1. A 12-element array.
[View full size image]
An index must be a nonnegative integer. A program can use an expression as an index. For example, if we assume that variable a is 5 and variable b is 6, then the statement
c[ a + b ] += 2;
adds 2 to array element c[ 11 ]. Note that an indexed array name is an array-access expression. Such expressions can be used on the left side of an assignment to place a new value into an array element.
Common Programming Error 7.1
Using a value of type long as an array index results in a compilation error. An index must be an int value or a value of a type that can be promoted to intnamely, byte, short or char, but not long.
Let us examine array c in Fig. 7.1 more closely. The name of the array is c. Every array object knows its own length and maintains this information in a length field. The expression c.length accesses array c's length field to determine the length of the array. Note that, even though the length member of an array is public, it cannot be changed because it is a final variable. This array's 12 elements are referred to as c[ 0 ], c[ 1 ], c[ 2 ], ..., c[ 11 ]. The value of c[ 0 ] is -45, the value of c[ 1 ] is 6, the value of c[ 2 ] is 0, the value of c[ 7 ] is 62 and the value of c[ 11 ] is 78. To calculate the sum of the values contained in the first three elements of array c and store the result in variable sum, we would write
[Page 288]
sum = c[ 0 ] + c[ 1 ] + c[ 2 ];
To divide the value of c[ 6 ] by 2 and assign the result to the variable x, we would write
x = c[ 6 ] / 2;
[Page 289]
When an array is declared, the type of the array and the square brackets can be combined at the beginning of the declaration to indicate that all the identifiers in the declaration are array variables. For example, the declaration
double[] array1, array2;
indicates that array1 and array2 are "array of double" variables. The preceding declaration is equivalent to:
double array1[]; double array2[];
or
double[] array1; double[] array2;
The preceding pairs of declarations are equivalentwhen only one variable is declared in each declaration, the square brackets can be placed either after the type or after the array variable name.
Common Programming Error 7.3
Declaring multiple array variables in a single declaration can lead to subtle errors. Consider the declaration int[] a, b, c;. If a, b and c should be declared as array variables, then this declaration is correctplacing square brackets directly following the type indicates that all the identifiers in the declaration are array variables. However, if only a is intended to be an array variable, and b and c are intended to be individual int variables, then this declaration is incorrectthe declaration int a[], b, c; would achieve the desired result.
A program can declare arrays of any type. Every element of a primitive-type array contains a value of the array's declared type. Similarly, in an array of a reference type, every element is a reference to an object of the array's declared type. For example, every element of an int array is an int value, and every element of a String array is a reference to a String object.
