Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
7Arrays
OB J ECT IVES
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.
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
Lab Exercises Name:
Lab Exercise 1 — Duplicate Elimination
282 Arrays Chapter7
Sample Output
Program Template
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
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.)
Lab Exercises Name:
Lab Exercise 1 — Duplicate Elimination
Chapter 7 Arrays 283
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.
Solution
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
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.
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 int numbers[] = new int[ 5 ]; // list of unique numbers
13 int count = 0; // number of uniques read
14 int entered = 0; // number of entered numbers
15
Fig. L 7.1 | Unique.java. (Part 2 of 2.)
Lab Exercises Name:
Lab Exercise 1 — Duplicate Elimination
284 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 {
24 // 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 ] )
34 containsNumber = true;
35
36 // add only if the number is not there already
37 if ( !containsNumber )
38 {
39 numbers[ count ] = number;
40 count++;
41 } // end if
42 else
43 System.out.printf( "%d has already been entered\n", number );
44 } // end if
45 else
46 System.out.println( "number must be between 10 and 100" );
47
48 // print the list
49 for ( int i = 0; i < count; i++ )
50 System.out.printf( "%d ", numbers[i] );
51
52 System.out.println();
53 } // end while
54 } // end method getNumbers
55 } // end class Unique
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
Lab Exercises Name:
Lab Exercise 1 — Duplicate Elimination
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.
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 int numbers[] = new int[ 30 ]; // list of unique numbers
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 int number = input.nextInt();
20
21 // validate the input
22 if ( 10 <= number && number <= 500 )
23 {
24 // 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 ] )
34 containsNumber = true;
35
36 // add only if the number is not there already
37 if ( !containsNumber )
38 {
39 numbers[ count ] = number;
40 count++;
41 } // end if
42 else
43 System.out.printf( "%d has already been entered\n",
44 number );
45 } // end if
46 else
47 System.out.println( "number must be between 10 and 100" );
48
49 // 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
54 } // end method getNumbers
55 } // end class Unique
Lab Exercises Name:
Lab Exercise 1 — Duplicate Elimination
286 Arrays Chapter7
2. Modify the program in Follow-Up Question 1 to allow the user to enter numbers until the array is full.
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
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 int numbers[] = new int[ 30 ]; // list of unique numbers
13 int count = 0; // number of uniques read
14
15 while( count < numbers.length )
16 {
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
24 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 )
34 {
35 numbers[ count ] = number;
36 count++;
37 } // end if
38 else
39 System.out.printf( "%d has already been entered\n",
40 number );
41 } // end if
42 else
43 System.out.println( "number must be between 10 and 100" );
Lab Exercises Name:
Lab Exercise 1 — Duplicate Elimination
Chapter 7 Arrays 287
3. Modify your solution to Follow-Up Question 2 to allow the user to enter the size of the array as the ap-
plication begins execution.
44
45 // print the list
46 for ( int i = 0; i < count; i++ )
47 System.out.printf( "%d ", numbers[i] );
48 System.out.println();
49 } // 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
4 {
5 public static void main( String args[] )
6 {
7 Unique application = new Unique();
8 application.getNumbers();
9 } // end main
10 } // end class UniqueTest
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 System.out.print( "How many numbers will you enter? " );
13 int number = input.nextInt();
14
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
24 if ( 10 <= number && number <= 500 )
25 {
26 // flags whether this number already exists
27 boolean containsNumber = false;
28
Lab Exercises Name:
Lab Exercise 1 — Duplicate Elimination
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;
34
35 // add only if the number is not there already
36 if ( !containsNumber )
37 {
38 numbers[ count ] = number;
39 count++;
40 } // end if
41 else
42 System.out.printf( "%d has already been entered\n",
43 number );
44 } // end if
45 else
46 System.out.println( "number must be between 10 and 100" );
47
48 // print the list
49 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
54 } // end class Unique
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
Lab Exercises Name:
Debugging
Chapter 7 Arrays 297
Name: Date:
Section:
Debugging
The program in this section does not run properly. Fix all the compilation errors, so that the program will com-
pile 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
Broken Code
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
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.)
Lab Exercises Name:
Debugging
298 Arrays Chapter7
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.)
Lab Exercises Name:
Debugging
Chapter 7 Arrays 299
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
Lab Exercises Name:
Debugging
300 Arrays Chapter7
Solution
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();
16
17 while ( person != -1 )
18 {
19 System.out.print( "Enter product number: " );
20 int product = input. ();
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 ] = 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[ row ][ column ] );
Fig. L 7.7 | Sales2.java
[][]
nextInt
>= <
Lab Exercises Name:
Debugging
Chapter 7 Arrays 301
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 40—Array salesPersonTotal should be indexed only with the value of column.
• Lines 54–56—Array sales should be indexed with row first, then column.
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
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
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.8 | Sales2Test.java
Fig. L 7.7 | Sales2.java