Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
630
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

b.Method fahrenheit returns the Fahrenheit equivalent of a Celsius temperature, using the calculation

F = 9.0 / 5.0 * C + 32;

c.Use the methods from parts (a) and (b) to write an application that enables the user either to enter a Fahrenheit temperature and display the Celsius equivalent or to enter a Celsius temperature and display the Fahrenheit equivalent.

6.23Write a method minimum3 that returns the smallest of three floating-point numbers. Use the Math.min method to implement minimum3. Incorporate the method into an application that reads three values from the user, determines the smallest value and displays the result.

6.24An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a method perfect that determines whether parameter number is a perfect number. Use this method in an application that determines and displays all the perfect numbers between 1 and 1000. Display the factors of each perfect number to confirm that the number is indeed perfect. Challenge the computing power of your computer by testing numbers much larger than 1000. Display the results.

6.25 An integer is said to be prime if it is divisible by only 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.

a.Write a method that determines whether a number is prime.

b.Use this method in an application that determines and displays all the prime numbers less than 10,000. How many numbers up to 10,000 do you have to test to ensure that you have found all the primes?

c.Initially, you might think that n/2 is the upper limit for which you must test to see whether a number is prime, but you need only go as high as the square root of n. Why? Rewrite the program, and run it both ways. Estimate the performance improvement.

6.26Write a method that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the method should return 1367. Incorporate the method into an application that reads a value from the user and displays the result.

6.27The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers. Write a method gcd that returns the greatest common divisor of two integers. Incorporate the method into an application that reads two values from the user and displays the result.

6.28Write a method qualityPoints that inputs a student's average and returns 4 if the student's average is 90100, 3 if the average is 8089, 2 if the average is 7079, 1 if the average is 6069 and 0 if the average is lower than 60. Incorporate the method into an application that reads a value from the user and displays the result.

6.29Write an application that simulates coin tossing. Let the program toss a coin each time the user chooses the "Toss Coin" menu option. Count the number of times each side of the coin appears. Display the results. The program should call a separate method flip that takes no arguments and returns false for tails and TRue for heads. [Note : If the program realistically simulates coin tossing, each side of the coin should appear approximately half the time.]

[Page 283]

6.30Computers are playing an increasing role in education. Write a program that will help an elementary school student learn multiplication. Use a Random object to produce two positive one-digit integers. The program should then prompt the user with a question, such as

How much is 6 times 7?

The student then inputs the answer. Next, the program checks the student's answer.

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 288 (continued)]

7.3. Declaring and Creating Arrays

Array objects occupy space in memory. Like other objects, arrays are created with keyword new. To create an array object, the programmer specifies the type of the array elements and the number of elements as part of an array-creation expression that uses keyword new. Such an expression returns a reference that can be stored in an array variable. The following declaration and array-creation expression create an array object containing 12 int elements and store the array's reference in variable c:

int c[] = new int[ 12 ];

This expression can be used to create the array shown in Fig. 7.1. This task also can be performed in two steps as follows:

int

c[];

//

declare

the

array

variable

c =

new int[ 12 ];

//

create

the

array;

assign to array variable

In the declaration, the square brackets following the variable name c indicate that c is a variable that will refer to an array (i.e., the variable will store an array reference). In the assignment statement, the array variable c receives the reference to a new array of 12 int elements. When an array is created, each element of the array receives a default valuezero for the numeric primitive-type elements, false for boolean elements and null for references (any nonprimitive type). As we will soon see, we can provide specific, nondefault initial element values when we create an array.

Common Programming Error 7.2

In an array declaration, specifying the number of elements in the square brackets of the declaration (e.g., int c[ 12 ];) is a syntax error.

A program can create several arrays in a single declaration. The following String array declaration reserves 100 elements for b and 27 elements for x:

String b[] = new String[ 100 ], x[] = new String[ 27 ];

In this case, the class name String applies to each variable in the declaration. For readability, we prefer to declare only one variable per declaration, as in:

String b[] = new String[ 100 ]; // create array b

String x[] = new String[ 27 ]; // create array x

Good Programming Practice 7.1

For readability, declare only one variable per declaration. Keep each declaration on a separate line, and include a comment describing the variable being declared.

[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.