Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis

Preview:

DESCRIPTION

Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 7. Code Listing 7-1 (ArrayDemo1.java) 1 import java.util.Scanner; // Needed for Scanner class 2 3 /** 4 This program shows values being stored in an array’s - PowerPoint PPT Presentation

Citation preview

Starting Out with Java: From Control Structures

through Objects

5th edition

By Tony Gaddis

Source Code: Chapter 7

Code Listing 7-1 (ArrayDemo1.java)1 import java.util.Scanner; // Needed for Scanner class23 /**4 This program shows values being stored in an array’s5 elements and displayed.6 */78 public class ArrayDemo19 {

10 public static void main(String[] args)11 {12 final int EMPLOYEES = 3; // Number of employees

13 int[] hours = new int[EMPLOYEES]; // Array of hours1415 // Create a Scanner object for keyboard input.16 Scanner keyboard = new Scanner(System.in);1718 System.out.println("Enter the hours worked by " +19 EMPLOYEES + " employees.");20

(Continued)

21 // Get the hours worked by employee 1.22 System.out.print("Employee 1: ");

23 hours[0] = keyboard.nextInt();2425 // Get the hours worked by employee 2.26 System.out.print("Employee 2: ");

27 hours[1] = keyboard.nextInt();2829 // Get the hours worked by employee 3.30 System.out.print("Employee 3: ");

31 hours[2] = keyboard.nextInt();3233 // Display the values entered.34 System.out.println("The hours you entered are:");

35 System.out.println(hours[0]);36 System.out.println(hours[1]);37 System.out.println(hours[2]);38 }39 }

(Continued)

Program Output

Enter the hours worked by 3 employees.Employee 1: 40 [Enter]Employee 2: 20 [Enter]Employee 3: 15 [Enter]

The hours you entered are:402015

Code Listing 7-2 (ArrayDemo2.java)1 import java.util.Scanner; // Needed for Scanner class23 /**4 This program shows an array being processed with loops.5 */6

7 public class ArrayDemo28 {

9 public static void main(String[] args)

10 {11 final int EMPLOYEES = 3; // Number of employees

12 int[] hours = new int[EMPLOYEES]; // Array of hours

1314 // Create a Scanner object for keyboard input.

15 Scanner keyboard = new Scanner(System.in);16

17 System.out.println("Enter the hours worked by " +

18 EMPLOYEES + " employees.");1920 // Get the hours for each employee.

21 for (int index = 0; index < EMPLOYEES; index++ )

22 {(Continued)

23 System.out.print("Employee " + (index + 1) + ": ");

24 hours[ index ] = keyboard.nextInt();

25 }26

27 System.out.println("The hours you entered are:");

2829 // Display the values entered.

30 for (int index = 0; index < EMPLOYEES; index++ )31 System.out.println( hours[ index ] );

32 }33 }

Program Output with Example Input Shown in Bold

Enter the hours worked by 3 employees.Employee 1: 40 [Enter]Employee 2: 20 [Enter]Employee 3: 15 [Enter]

The hours you entered are:402015

Code Listing 7-3 (InvalidSubscript.java)1 /**2 This program uses an invalid subscript with an array.3 */4

5 public class InvalidSubscript6 {

7 public static void main(String[] args)8 {

9 int[] values = new int[3];1011 System.out.println("I will attempt to store four " +12 "numbers in a three-element array.");13

14 for ( int index = 0; index < 4; index++ )15 {16 System.out.println("Now processing element " + index);17 values[index] = 10;18 }19 }20 }

(Continued)

Program Output

I will attempt to store four numbers in a three-element array.Now processing element 0Now processing element 1Now processing element 2Now processing element 3Exception in thread "main“

java.lang.ArrayIndexOutOfBoundsException: 3 at InvalidSubscript.main(InvalidSubscript.java:17)

Code Listing 7-4 (ArrayInitialization.java)1 /**

2 This program shows an array being initialized.3 */4

5 public class ArrayInitialization6 {

7 public static void main(String[] args)8 {

9 int[] days = { 31, 28, 31, 30, 31, 30,10 31, 31, 30, 31, 30, 31 };11

12 for (int index = 0; index < 12; index++)13 {14 System.out.println("Month " + (index + 1) +15 " has " + days[index] +16 " days.");17 }18 }19 } // Valid subscripts in for-loop?

(Continued)

Program OutputMonth 1 has 31 days.Month 2 has 28 days.Month 3 has 31 days.Month 4 has 30 days.Month 5 has 31 days.Month 6 has 30 days.Month 7 has 31 days.Month 8 has 31 days.Month 9 has 30 days.Month 10 has 31 days.Month 11 has 30 days.Month 12 has 31 days.

Code Listing 7-5 (PayArray.java)1 import java.util.Scanner; // Needed for Scanner class23 /**4 This program stores in an array the hours worked by5 five employees who all make the same hourly wage.6 */78 public class PayArray9 {10 public static void main(String[] args)11 {12 final int EMPLOYEES = 5; 13 double payRate; 14 double grossPay; 1516

17 int[] hours = new int[EMPLOYEES];1819 20 Scanner keyboard = new Scanner(System.in);21

(Continued)

23 System.out.println("Enter the hours worked by " +24 EMPLOYEES + " employees who all earn " +25 "the same hourly rate.");26

27 for (int index = 0; index < EMPLOYEES; index++)28 {29 System.out.print( "Employee #" + (index + 1) + ": ");

30 hours[index] = keyboard.nextInt();31 }3233 34 System.out.print("Enter the hourly rate for each employee: ");35 payRate = keyboard.nextDouble();36 System.out.println( "Here is each employee's gross pay:“ );

39 for (int index = 0; index < EMPLOYEES; index++)40 {41 grossPay = hours[index] * payRate;42 System.out.println("Employee #" + (index + 1) +43 ": $" + grossPay);

44 }

(Continued)

45 } // End main46 } // End Class

Program Output with Example Input Shown in Bold

Enter the hours worked by 5 employees who all earn the same hourly rate.Employee #1: 10 [Enter]Employee #2: 20 [Enter]Employee #3: 30 [Enter]Employee #4: 40 [Enter]Employee #5: 50 [Enter]

Enter the hourly rate for each employee: 10 [Enter]

Here is each employee's gross pay:Employee #1: $100.0Employee #2: $200.0Employee #3: $300.0Employee #4: $400.0Employee #5: $500.0.

Code Listing 7-6 (DisplayTestScores.java)1 import java.util.Scanner; // Needed for Scanner class23 /**

4 This program demonstrates how the user may specify an

5 array's size.6 */7

8 public class DisplayTestScores9 {

10 public static void main(String[] args)11 {

12 int numTests; 13 int[] tests; // Is memory allocated?1416 Scanner keyboard = new Scanner(System.in);1718

19 System.out.print("How many tests do you have? ");

20 numTests = keyboard.nextInt();21

23 tests = new int[numTests];(Continued)

26 for (int index = 0; index < tests.length; index++)27 {28 System.out.print("Enter test score " +29 (index + 1) + ": ");30 tests[index] = keyboard.nextInt();31 }3234 System.out.println();35 System.out.println("Here are the scores you entered:");

36 for (int index = 0; index < tests.length; index++)37 System.out.print( tests[index] + " ");38 }39 }

Program Output with Example Input Shown in BoldHow many tests do you have? 5 [Enter]Enter test score 1: 72 [Enter]Enter test score 2: 85 [Enter]Enter test score 3: 81 [Enter]Enter test score 4: 94 [Enter]Enter test score 5: 99 [Enter]

Here are the scores you entered:72 85 81 94 99

Code Listing 7-7 ( SameArray.java )1 /**

2 This program demonstrates that two variables can3 reference the same array.4 */5

6 public class SameArray7 {

8 public static void main(String[] args)

9 {

10 int[] array1 = { 2, 4, 6, 8, 10 };11 int[] array2 = array1;12

14 array1[0] = 200;15

17 array2[4] = 1000;18

20 System.out.println("The contents of array1:");

21 for ( int value : arrayl )

22 System.out.print(value + " ");23 System.out.println();

(Continued)

2425

26 System.out.println("The contents of array2:");

27 for (int value : array2)

28 System.out.print(value + " ");29 System.out.println();30 }31 }

Program Output

The contents of array1:200 4 6 8 1000

The contents of array2:200 4 6 8 1000

Code Listing 7-8 (PassElements.java)1 /**2 This program demonstrates passing individual array3 elements as arguments to a method.4 */56 public class PassElements7 {8 public static void main(String[] args)9 {10 int[] numbers = {5, 10, 15, 20, 25, 30, 35, 40};11

12 for (int index = 0; index < numbers.length; index++)13 showValue( numbers[index] );14 }1516 /**17 The showValue method displays its argument.18 @param n The value to display.19 */2021 public static void showValue(int n)22 {23 System.out.print( n + " ");24 }25 }Program Output

5 10 15 20 25 30 35 40

Code Listing 7-9 (PassArray.java)

1 import java.util.Scanner; // Needed for Scanner class23 /**4 This program demonstrates passing an array5 as an argument to a method.6 */78 public class PassArray9 {10 public static void main(String[] args)11 {12 final int ARRAY_SIZE = 4; 1314 15 int[] numbers = new int[ARRAY_SIZE];1617 18 getValues( numbers );1920 System.out.println("Here are the " +21 "numbers that you entered:");

(Continued)

2223

24 showArray( numbers );25 } // End main2627 /**28 The getValues method accepts a reference29 to an array as its argument. The user is30 asked to enter a value for each element.31 @param array A reference to the array.32 */33

34 private static void getValues( int[] array )35 {36 37 Scanner keyboard = new Scanner(System.in);3839 System.out.println("Enter a series of " +

40 array.length + " numbers.“ );

41

(Continued)

43 for (int index = 0; index < array.length; index++ )44 {45 System.out.print("Enter number " +46 (index + 1) + ": ");47 array[index] = keyboard.nextInt();48 }49 }5051 /**52 The showArray method accepts an array as53 an argument and displays its contents.54 @param array A reference to the array.55 */5657 public static void showArray(int[] array)58 {59

60 for (int index = 0; index < array.length; index++ )61 System.out.print( array[index] + " “ );62 }63 } // End Class

(Continued)

Program Output with Example Input Shown in Bold

Enter a series of 4 numbers.Enter number 1: 2 [Enter]Enter number 2: 4 [Enter]Enter number 3: 6 [Enter]Enter number 4: 8 [Enter]

Here are the numbers that you entered:

2 4 6 8

Code Listing 7-10 (SalesData.java)

1 /**2 This class keeps the sales figures for a number of3 days in an array and provides methods for getting4 the total and average sales, and the highest and5 lowest amounts of sales.6 */78 public class SalesData9 {

10 private double[] sales; // The sales data field1112 /**13 The constructor constructor copies the elements in14 an array to the sales array.15 @param s The array to copy.16 */17

18 public SalesData(double[] s)19 {20

21 sales = new double[ s.length ];22

(Continued)

24 for (int index= 0; index < s.length; index++)

25 sales[index] = s[index];

26 }

27

28 /**

2929 getTotal methodgetTotal method

30 @return The total of the elements in

31 the sales array.

32 */

33

34 public double getTotal()

35 {

36 double total = 0;

37

38 // Accumulate the sum of values in the sales array.

40 for (int index = 0; index < sales.length; index++)41 total += sales[index];4243

44 return total;45 }4647 /**48 getAverage method49 @return The average of the elements50 in the sales array.51 */52

53 public double getAverage()54 {

55 return getTotal() / sales.length;56 }5758 /**59 getHighest method60 @return The highest value stored61 in the sales array.62 */

(Continued)

63

64 public double getHighest()65 {

66 double highest = sales[0];67

68 for (int index = 1; index < sales.length; index++)69 {

70 if (sales[index] > highest)71 highest = sales[index];72 }73

74 return highest;75 }7677 /**

78 getLowest method79 @return The lowest value stored80 in the sales array.81 */82

(Continued)

83 public double getLowest()84 {

85 double lowest = sales[0];86

87 for (int index = 1; index < sales.length; index++)88 {

89 if (sales[index] < lowest)90 lowest = sales[index];91 }92

93 return lowest;94 }95 }

Code Listing 7-11 (Sales.java)

1 import javax.swing.JOptionPane;2 import java.text.DecimalFormat;34 /**5 This program gathers sales amounts for the week.6 It uses the SalesData class to display the total,7 average, highest, and lowest sales amounts.8 */910 public class Sales11 {12 public static void main(String[] args)13 {14 final int ONE_WEEK = 7; 1517 double[] sales = new double[ONE_WEEK];1820 getValues(sales);21

(Continued)

22 // Create a SalesData object.

24 SalesData week = new SalesData(sales);2527 DecimalFormat dollar = new DecimalFormat("#,##0.00");2829 // Display the total, average, highest, and lowest30 // sales amounts for the week.

31 JOptionPane.showMessageDialog(null,32 "The total sales were $" +33 dollar.format( week.getTotal() ) +34 "\nThe average sales were $" +35 dollar.format( week.getAverage() ) +36 "\nThe highest sales were $" +37 dollar.format( week.getHighest() ) +38 "\nThe lowest sales were $" +39 dollar.format( week.getLowest() ));4041 System.exit(0);

42 } // end main()43

(Continued)

44 /**

45 The getValues method asks the user to enter sales

46 amounts for each element of an array.47 @param array The array to store the values in.48 */49

50 private static void getValues(double[] array)51 {52 String input; 53

54 // Get sales for each day of the week.

55 for (int i = 0; i < array.length; i++)

56 {57 input = JOptionPane.showInputDialog("Enter " +58 "the sales for day " + (i + 1) + ".");

59 array[i] = Double.parseDouble(input);60 }61 }62 } // end class

Code Listing 7-12 (Grader.java)1 /**2 The Grader class calculates the average3 of an array of test scores, with the4 lowest score dropped.5 */6

7 public class Grader8 {

12 private double[] testScores;1314 /**

15 Constructor16 @param scoreArray An array of test scores.17 */18

19 public Grader( double[] scoreArray )20 {

(Continued)

21 // Assign the array argument to data field.22

23 testScores = scoreArray; // What is stored in “testscores”?24 } // end constructor25---------------------------------------------------------------------------------------------------------------------------------26 /**

27 getLowestScore method28 @return The lowest test score.29 */30

31 public double getLowestScore()32 {33 double lowest; 34

36 lowest = testScores[0]; // Why is “testscores” usable?3739

41 for (int index = 1; index < testScores.length; index++)42 {

43 if (testScores[index] < lowest)(Continued)

44 lowest = testScores[index];45 }4647 // Return the lowest test score.

48 return lowest;49 }50---------------------------------------------------------------------------------------------------------------------------------51 /**

52 getAverage method53 @return The average of the test scores54 with the lowest score dropped.55 */56

57 public double getAverage()58 {

59 double total = 0; // To hold the score total

60 double lowest; // To hold the lowest score

61 double average; // To hold the average

6263 65

66 if (testScores.length < 2)(Continued)

67 {68 System.out.println("ERROR: You must have at " +69 "least two test scores!");70 average = 0;71 }

72 else73 {74

75 for (double score : testScores) // Enhanced for-loopEnhanced for-loop76 total += score;7778

79 lowest = getLowestScore();8081 // Subtract the lowest score from the total.)

82 total -= lowest;8384 // Get the adjusted average.

85 average = total / (testScores.length - 1);86 }8788

89 return average;90 } // end method91 } // end class

Code Listing 7-13 (CalcAverage.java)1 import java.util.Scanner;23 /**4 This program gets a set of test scores and5 uses the Grader class to calculate the average6 with the lowest score dropped.7 */89 public class CalcAverage10 {11 public static void main(String[] args)12 {13 int numScores; // To hold the number of scores14

16 Scanner keyboard = new Scanner(System.in);17

19 System.out.print("How many test scores do you have? ");

20 numScores = keyboard.nextInt();21

(Continued)

22 // Create an array to hold the test scores.

23 double[] scores = new double[numScores];2425 // Get the test scores and store them.26

27 for (int index = 0; index < numScores; index++ )28 {29 System.out.print("Enter score #" +30 (index + 1) + ": ");31 scores[index] = keyboard.nextDouble();32 }33

37 Grader myGrader = new Grader( scores );38

40 System.out.println("Your adjusted average is " +41 myGrader.getAverage());42

(Continued)

43 // Display the lowest score.

44 System.out.println("Your lowest test score was " +

45 myGrader.getLowestScore());4647 }48 }

Program Output with Example Input Shown in Bold

How many test scores do you have? 4 [ Enter ]

Enter score #1: 100 [ Enter ]Enter score #2: 100 [ Enter ]Enter score #3: 40 [ Enter ]Enter score #4: 100 [ Enter ]

Your adjusted average is 100.0Your lowest test score was 40.0

Code Listing 7-14 (ReturnArray.java)1 /**2 This program demonstrates how a reference to an3 array can be returned from a method.4 */56 public class ReturnArray7 {8 public static void main(String[] args)9 {10 double[] values;11

12 values = getArray();

13 for (double num : values)14 System.out.print(num + " ");15 }1617 /**18 getArray method19 @return A reference to an array of doubles.20 */21

(Continued)

22 public static double[] getArray()23 {

24 double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 };25

26 return array;27 }28 }

Program Output

1.2 2.3 4.5 6.7 8.9

Code Listing 7-15 (MonthDays.java)1 /**2 This program demonstrates an array of String objects.3 */45 public class MonthDays6 {7 public static void main(String[] args)8 {9 String[] months = { "January", "February", "March",10 "April", "May", "June", "July",11 "August", "September", "October",12 "November", "December" };13

14 int[ ] days = { 31, 28, 31, 30, 31, 30, 31,15 31, 30, 31, 30, 31 };16

17 for (int index = 0; index < months.length; index++)18 {19 System.out.println( months[index] + " has " +20 days[index] + " days.");21 }22 }23 }

(Continued)

Program Output

January has 31 days.February has 28 days.March has 31 days.April has 30 days.May has 31 days.June has 30 days.July has 31 days.August has 31 days.September has 30 days.October has 31 days.November has 30 days.December has 31 days.

Code Listing 7-16 (ObjectArray.java)

1 import java.util.Scanner; 3 /**

4 This program works with an array of three5 BankAccount objects.6 */7

8 public class ObjectArray9 {10 public static void main(String[] args)

11 {12 final int NUM_ACCOUNTS = 3; 1314 // Create an array of BankAccount objects.

16 BankAccount[ ] accounts = new BankAccount[NUM_ACCOUNTS];17

19 createAccounts(accounts);2021

22 System.out.println("Here are the balances " +23 "for each account:");

(Continued)

24

25 for (int index = 0; index < accounts.length; index++)26 {27 System.out.println("Account " + (index + 1) +

28 ": $" + accounts[index].getBalance() );29 }30 }3132 /**33 The createAccounts method creates a BankAccount34 object for each element of an array. The user35 Is asked for each account's balance.36 @param array The array to reference the accounts37 */38

39 private static void createAccounts(BankAccount[ ] array)40 {

41 double balance; 4243

44 Scanner keyboard = new Scanner(System.in);45

(Continued)

46 // Create the accounts.

47 for (int index = 0; index < array.length; index++)48 {49 50 System.out.print("Enter the balance for " +51 "account " + (index + 1) + ": ");52 balance = keyboard.nextDouble();5354 55 array[index] = new BankAccount(balance);56 }57 }58 }

Program Output with Example Input Shown in BoldEnter the balance for account 1: 2500.0 [Enter]Enter the balance for account 2: 5000.0 [Enter]Enter the balance for account 3: 1500.0 [Enter]

Here are the balances for each account:Account 1: $2500.0Account 2: $5000.0Account 3: $1500.0

Code Listing 7-17 (SearchArray.java)1 /**

2 This program sequentially searches an3 int array for a specified value.4 */56 public class SearchArray7 {8 public static void main(String[ ] args)9 {10 int[ ] tests = { 87, 75, 98, 100, 82 };11 int results;12

14 results = sequentialSearch(tests, 100);16

17 if (results == -1)19 {20 System.out.println("You did not " +21 "earn 100 on any test.");

(Continued)

22 }

23 else24 {25 System.out.println("You earned 100 " +26 "on test " + (results + 1));27 }

28 } // end main()2930 /**

31 The sequentialSearch method searches an array for32 a value.33 @param array The array to search.34 @param value The value to search for.35 @return The subscript of the value if found in the36 array, otherwise -1.37 */38

39 public static int sequentialSearch(int[ ] array, int value)41 {

42 int index;

43 int element;

44 boolean found; (Continued)

46 47 index = 0;48

50 element = -1;51 found = false;5253 // Search the array.

54 while (!found && index < array.length)55 {56 if (array[index] == value) // FOUND IT!FOUND IT!57 {58 found = true;59 element = index; // HERE!HERE!60 }61 index++;62 }63

64 return element; // What are possible return values?What are possible return values?65 } // end search66 } // end class

Program OutputYou earned 100 on test 4

Code Listing 7-18 (CorpSales.java)1 import java.util.Scanner;23 /**

4 This program demonstrates a two-dimensional array.5 */67 public class CorpSales8 {9 public static void main(String[] args)10 {11 final int DIVS = 3; // Three divisions in the company12 final int QTRS = 4; // Four quarters13 double totalSales = 0.0; 1415 16

17 double[ ][ ] sales = new double[DIVS][QTRS];1819 20 Scanner keyboard = new Scanner(System.in);21

(Continued)

23 System.out.println("This program will calculate the " +24 "total sales of");25 System.out.println("all the company's divisions. " );26 2728 // Nested loops. WHY!

30 for (int div = 0; div < DIVS; div++ )31 {32 for (int qtr = 0; qtr < QTRS; qtr++ )33 {34 System.out.printf("Division %d, Quarter %d: $",35 (div + 1), (qtr + 1));36 sales[div][qtr] = keyboard.nextDouble();37 }38 System.out.println(); 39 }4041 // Nested loops to add all the elements of the array.

42 for ( int div = 0; div < DIVS; div++ )43 {

44 for ( int qtr = 0; qtr < QTRS; qtr++ )

45 {

46 totalSales += sales[div][qtr];47 }48 }49

50 // Display the total sales.51 System.out.printf("Total company sales: $%,.2f\n",

52 totalSales);

53 }54 }

Program Output with Example Input Shown in Bold

This program will calculate the total sales ofall the company's divisions. Enter the following sales data:

Division 1, Quarter 1: $ 35698.77 [Enter]Division 1, Quarter 2: $ 36148.63 [Enter]Division 1, Quarter 3: $ 31258.95 [Enter]Division 1, Quarter 4: $ 30864.12 [Enter]

(Continued)

Division 2, Quarter 1: $ 41289.64 [Enter]Division 2, Quarter 2: $ 43278.52 [Enter]Division 2, Quarter 3: $ 40928.18 [Enter]Division 2, Quarter 4: $ 42818.98 [Enter]

Division 3, Quarter 1: $ 28914.56 [Enter]Division 3, Quarter 2: $ 27631.52 [Enter]Division 3, Quarter 3: $ 30596.64 [Enter]Division 3, Quarter 4: $ 29834.21 [Enter]

Total company sales: $419,262.72

Code Listing 7-19 (Lengths.java)1 /**

2 This program uses the length fieldslength fields of a 2D array3 to display the number of rows, and the number of4 columns in each row.5 */6

7 public class Lengths8 {

9 public static void main(String[ ] args)10 {11 13

14 int[][] numbers = { { 1, 2, 3, 4 },15 { 5, 6, 7, 8 },

16 { 9, 10, 11, 12 } }; // What is size of the array?17

19 System.out.println("The number of " +

20 "rows is " + numbers.length );21

22 // Display the number of columns in each row.

23 for (int index = 0; index < numbers.length; index++)24 {

25 System.out.println("The number of " +

26 "columns in row " + index + " is " +

27 numbers[index].length );28 }29 }30 }

Program Output

The number of rows is 3The number of columns in row 0 is 4The number of columns in row 1 is 4The number of columns in row 2 is 4

Code Listing 7-20 (Pass2Darray.java)1 /**2 This program demonstrates methods that accept3 a two-dimensional array as an argument.4 */56 public class Pass2Darray7 {8 public static void main(String[] args)9 {10 int[ ][ ] numbers = { { 1, 2, 3, 4 },11 { 5, 6, 7, 8 },12 { 9, 10, 11, 12 } };13

15 System.out.println("Here are the values " +16 " in the array.");

17 showArray(numbers);18

20 System.out.println("The sum of the values " +21 "is " + arraySum(numbers));22 }

(Continued)

2324 /**25 The showArray method displays the contents26 of a two-dimensional int array.27 @param array The array to display.28 */29

30 private static void showArray(int[ ][ ] array)31 {32 for (int row = 0; row < array.length; row++ )33 {34 for (int col = 0; col < array[row].length; col++ )

35 System.out.print( array[row][col] + " “ );

36 System.out.println();37 }38 }3940 /**41 The arraySum method returns the sum of the42 values in a two-dimensional int array.43 @param array The array to sum.44 @return The sum of the array elements.45 */

(Continued)

46

47 private static int arraySum(int[ ][ ] array)

48 {49 int total = 0; 50

51 for (int row = 0; row < array.length; row++ )52 {

53 for (int col = 0; col < array[row].length; col++ )

54 total += array[row][col];55 }5657 return total;

58 }59 } // End class----------------------------------------------------------------------------------------------------------

-Program Output

Here are the values in the array.1 2 3 45 6 7 89 10 11 12The sum of the values is 78

Code Listing 7-21 (CommandLine.java)1 /**

2 This program displays the arguments passed to3 it from the operating system command line.4 */5

6 public class CommandLine7 {

8 public static void main( String[ ] args )9 {

10 for (int index = 0; index < args.length; index++)

11 System.out.println( args[index] );12 }13 }

Code Listing 7-22 (VarargsDemo2.java)1 /**

2 This program demonstrates a method that accepts3 a variable number of arguments (varargs).4 */5

6 public class VarargsDemo27 {

8 public static void main(String[ ] args)9 {

10 double total; 1112

13 BankAccount account1 = new BankAccount(100.0);1415

16 BankAccount account2 = new BankAccount(500.0);1718

19 BankAccount account3 = new BankAccount(1500.0);2021

22 total = totalBalance(account1);

23 System.out.println("Total: $" + total);(Continued)

25 26 total = totalBalance(account1, account2);27 System.out.println("Total: $" + total);2829 30 total = totalBalance(account1, account2, account3);31 System.out.println("Total: $" + total);32 }3334 /**35 The totalBalance method takes a variable number36 of BankAccount objects and returns the total37 of their balances.38 @param accounts The target account or accounts.39 @return The sum of the account balances40 */41

42 public static double totalBalance(BankAccount... accounts)43 {44 double total = 0.0; // What is “accounts” ?

4546

47 for (BankAccount acctObject : accounts)

48 total += acctObject.getBalance();4950 // Return the total.

51 return total;52 }53 }

Program Output

Total: $100.0Total: $600.0Total: $2100.0

Code Listing 7-23 (ArrayListDemo1.java)1 import java.util.ArrayList; 23 /**

4 This program demonstrates an ArrayList.5 */67 public class ArrayListDemo18 {

9 public static void main(String[ ] args)10 {11

12 ArrayList<String> nameList = new ArrayList<String>();1314

15 nameList.add("James");16 nameList.add("Catherine");17 nameList.add("Bill");1819 System.out.println("The ArrayList has " +

21 nameList.size() +22 " objects stored in it.");

(Continued)

23

24 // Now display the items in nameList.

25 for (int index = 0; index < nameList.size(); index++)

26 System.out.println(nameList.get(index));27 }28 }

Program Output

The ArrayList has 3 objects stored in it.

JamesCatherineBill

Code Listing 7-24 (ArrayListDemo2.java)

1 import java.util.ArrayList; 23 /**

4 This program demonstrates how the enhanced for loop5 can be used with an ArrayList.6 */7

8 public class ArrayListDemo29 {

10 public static void main(String[] args)

11 {12

13 ArrayList<String> nameList = new ArrayList<String>();1415

16 nameList.add("James");17 nameList.add("Catherine");18 nameList.add("Bill");19

20 System.out.println("The ArrayList has " + nameList.size() +22 " objects stored in it.");

(Continued)

24

25 // Now display the items in nameList.

26 for (String name : nameList)27 System.out.println(name);28 }29 }

Program Output

The ArrayList has 3 objects stored in it.JamesCatherineBill

Code Listing 7-25 (ArrayListDemo3.java)1 import java.util.ArrayList; 23 /**4 This program demonstrates an ArrayList.5 */6

7 public class ArrayListDemo38 {

9 public static void main(String[] args)10 {11

12 ArrayList<String> nameList = new ArrayList<String>();1314

15 nameList.add("James");16 nameList.add("Catherine");17 nameList.add("Bill");1819

20 for (int index = 0; index < nameList.size(); index++)21 {22 System.out.println("Index: " + index + " Name: " +23 nameList.get(index)); 24 }

26 // Now remove the item at index 1.

27 nameList.remove(1);2829 System.out.println("The item at index 1 is removed. " +30 "Here are the items now.“ );3132 33 for (int index = 0; index < nameList.size(); index++)34 {35 System.out.println("Index: " + index + " Name: " +36 nameList.get(index));37 }38 }39 }

Program OutputIndex: 0 Name: JamesIndex: 1 Name: CatherineIndex: 2 Name: BillThe item at index 1 is removed. Here are the items now.Index: 0 Name: JamesIndex: 1 Name: Bill

Code Listing 7-26 (ArrayListDemo4.java)1 import java.util.ArrayList; 23 /**

4 This program demonstrates inserting an item.5 */6

7 public class ArrayListDemo48 {

9 public static void main(String[ ] args)10 {11

12 ArrayList<String> nameList = new ArrayList<String>();1314

15 nameList.add("James");16 nameList.add("Catherine");17 nameList.add("Bill");1819 20 for (int index = 0; index < nameList.size(); index++)21 {

(Continued)

20 for(index = 0; index < nameList.size(); index++)21 {22 System.out.println("Index: " + index + " Name: " +

23 nameList.get(index));24 }2526 // Now insert an item at index 1.

27 nameList.add(1, "Mary");

2829 System.out.println("Mary was added at index 1. " +30 "Here are the items now.");3132

33 for (int index = 0; index < nameList.size(); index++)34 {35 System.out.println("Index: " + index + " Name: " +

36 nameList.get(index));37 }38 }39 }

(Continued)

Program OutputIndex: 0 Name: JamesIndex: 1 Name: CatherineIndex: 2 Name: Bill

Mary was added at index 1. Here are the items now.Index: 0 Name: JamesIndex: 1 Name: MaryIndex: 2 Name: CatherineIndex: 3 Name: Bill

Code Listing 7-27 (ArrayListDemo6.java)1 import java.util.ArrayList;

23 /**

4 This program demonstrates how to store BankAccount5 objects in an ArrayList.6 */7

8 public class ArrayListDemo69 {

10 public static void main(String[] args)

11 {12

13 ArrayList<BankAccount> list = new ArrayList<BankAccount>();1415 // Add three BankAccount objects to the ArrayList.

16 list.add(new BankAccount(100.0));

17 list.add(new BankAccount(500.0));

18 list.add(new BankAccount(1500.0));19

(Continued)

20 // Display each item.

21 for (int index = 0; index < list.size(); index++)22 {

23 BankAccount account = list.get(index);24 System.out.println("Account at index " + index +

25 "\nBalance: " + account.getBalance());26 }27 }28

Program Output

Account at index 0Balance: 100.0Account at index 1Balance: 500.0Account at index 2Balance: 1500.0

Recommended