Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with Java: From Control Structures through Objects

Similar presentations


Presentation on theme: "Starting Out with Java: From Control Structures through Objects"— Presentation transcript:

1 Starting Out with Java: From Control Structures through Objects
5th edition By Tony Gaddis Source Code: Chapter 7

2 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 5 elements and displayed. 6 */ 7 8 public class ArrayDemo1 9 { 10 public static void main(String[] args) 11 { 12 final int EMPLOYEES = 3; // Number of employees 13 int[] hours = new int[EMPLOYEES]; // Array of hours 14 15 // Create a Scanner object for keyboard input. 16 Scanner keyboard = new Scanner(System.in); 17 18 System.out.println("Enter the hours worked by " + EMPLOYEES + " employees."); 20 (Continued)

3 35 System.out.println(hours[0]); 36 System.out.println(hours[1]);
21 // Get the hours worked by employee 1. 22 System.out.print("Employee 1: "); 23 hours[0] = keyboard.nextInt(); 24 25 // Get the hours worked by employee 2. 26 System.out.print("Employee 2: "); 27 hours[1] = keyboard.nextInt(); 28 29 // Get the hours worked by employee 3. 30 System.out.print("Employee 3: "); 31 hours[2] = keyboard.nextInt(); 32 33 // 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)

4 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: 40 20 15

5 Code Listing 7-2 (ArrayDemo2.java)
1 import java.util.Scanner; // Needed for Scanner class 2 3 /** 4 This program shows an array being processed with loops. 5 */ 6 7 public class ArrayDemo2 8 { 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 13 14 // Create a Scanner object for keyboard input. 15 Scanner keyboard = new Scanner(System.in); 16 17 System.out.println("Enter the hours worked by " + EMPLOYEES + " employees."); 19 20 // Get the hours for each employee. 21 for (int index = 0; index < EMPLOYEES; index++ ) 22 { (Continued)

6 Program Output with Example Input Shown in Bold
23 System.out.print("Employee " + (index + 1) + ": "); 24 hours[ index ] = keyboard.nextInt(); 25 } 26 27 System.out.println("The hours you entered are:"); 28 29 // 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: 40 20 15

7 Code Listing 7-3 (InvalidSubscript.java)
1 /** 2 This program uses an invalid subscript with an array. 3 */ 4 5 public class InvalidSubscript 6 { 7 public static void main(String[] args) 8 { 9 int[] values = new int[3]; 10 11 System.out.println("I will attempt to store four " + "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)

8 Program Output I will attempt to store four numbers in a three-element array. Now processing element 0 Now processing element 1 Now processing element 2 Now processing element 3 Exception in thread "main“ java.lang.ArrayIndexOutOfBoundsException: 3 at InvalidSubscript.main(InvalidSubscript.java:17)

9 Code Listing 7-4 (ArrayInitialization.java)
1 /** 2 This program shows an array being initialized. 3 */ 4 5 public class ArrayInitialization 6 { 7 public static void main(String[] args) 8 { 9 int[] days = { 31, 28, 31, 30, 31, 30, , 31, 30, 31, 30, 31 }; 11 12 for (int index = 0; index < 12; index++) 13 { 14 System.out.println("Month " + (index + 1) + " has " + days[index] + " days."); 17 } 18 } 19 } // Valid subscripts in for-loop? (Continued)

10 Program Output Month 1 has 31 days. Month 2 has 28 days.

11 Code Listing 7-5 (PayArray.java)
1 import java.util.Scanner; // Needed for Scanner class 2 3 /** 4 This program stores in an array the hours worked by 5 five employees who all make the same hourly wage. 6 */ 7 8 public class PayArray 9 { 10 public static void main(String[] args) 11 { final int EMPLOYEES = 5; double payRate; double grossPay; 15 16 int[] hours = new int[EMPLOYEES]; 18 19 Scanner keyboard = new Scanner(System.in); 21 (Continued)

12 23 System.out.println("Enter the hours worked by " +
EMPLOYEES + " employees who all earn " + "the same hourly rate."); 26 27 for (int index = 0; index < EMPLOYEES; index++) 28 { System.out.print( "Employee #" + (index + 1) + ": "); hours[index] = keyboard.nextInt(); } 32 33 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 { grossPay = hours[index] * payRate; System.out.println("Employee #" + (index + 1) + ": $" + grossPay); } (Continued)

13 Program Output with Example Input Shown in Bold
45 } // End main 46 } // 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.0 Employee #2: $200.0 Employee #3: $300.0 Employee #4: $400.0 Employee #5: $500.0.

14 Code Listing 7-6 (DisplayTestScores.java)
1 import java.util.Scanner; // Needed for Scanner class 2 3 /** 4 This program demonstrates how the user may specify an 5 array's size. 6 */ 7 8 public class DisplayTestScores 9 { 10 public static void main(String[] args) 11 { 12 int numTests; 13 int[] tests; // Is memory allocated? 14 16 Scanner keyboard = new Scanner(System.in); 17 18 19 System.out.print("How many tests do you have? "); 20 numTests = keyboard.nextInt(); 21 23 tests = new int[numTests]; (Continued)

15 Program Output with Example Input Shown in Bold
26 for (int index = 0; index < tests.length; index++) { 28 System.out.print("Enter test score " + (index + 1) + ": "); 30 tests[index] = keyboard.nextInt(); } 32 34 System.out.println(); System.out.println("Here are the scores you entered:"); 36 for (int index = 0; index < tests.length; index++) System.out.print( tests[index] + " "); 38 } 39 } Program Output with Example Input Shown in Bold How 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:

16 23 System.out.println(); Code Listing 7-7 ( SameArray.java ) 1 /**
1 /** 2 This program demonstrates that two variables can 3 reference the same array. 4 */ 5 6 public class SameArray 7 { 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)

17 Program Output The contents of array1: 200 4 6 8 1000
24 25 System.out.println("The contents of array2:"); 27 for (int value : array2) System.out.print(value + " "); 29 System.out.println(); 30 } 31 } Program Output The contents of array1: The contents of array2:

18 Code Listing 7-8 (PassElements.java)
1 /** 2 This program demonstrates passing individual array 3 elements as arguments to a method. 4 */ 5 6 public class PassElements 7 { 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 } 15 16 /** 17 The showValue method displays its argument. 18 @param n The value to display. 19 */ 20 21 public static void showValue(int n) 22 { 23 System.out.print( n + " "); 24 } 25 } Program Output

19 Code Listing 7-9 (PassArray.java)
1 import java.util.Scanner; // Needed for Scanner class 2 3 /** 4 This program demonstrates passing an array 5 as an argument to a method. 6 */ 7 8 public class PassArray 9 { 10 public static void main(String[] args) 11 { 12 final int ARRAY_SIZE = 4; 13 14 15 int[] numbers = new int[ARRAY_SIZE]; 16 17 18 getValues( numbers ); 19 20 System.out.println("Here are the " + "numbers that you entered:"); (Continued)

20 22 23 24 showArray( numbers ); 25 } // End main 26 27 /** 28 The getValues method accepts a reference 29 to an array as its argument. The user is 30 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 Scanner keyboard = new Scanner(System.in); 38 System.out.println("Enter a series of " + array.length + " numbers.“ ); 41 (Continued)

21 43 for (int index = 0; index < array.length; index++ ) 44 {
44 { 45 System.out.print("Enter number " + (index + 1) + ": "); 47 array[index] = keyboard.nextInt(); } 49 } 50 51 /** 52 The showArray method accepts an array as 53 an argument and displays its contents. 54 @param array A reference to the array. 55 */ 56 57 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)

22 2 4 6 8 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:

23 Code Listing 7-10 (SalesData.java)
1 /** 2 This class keeps the sales figures for a number of 3 days in an array and provides methods for getting 4 the total and average sales, and the highest and 5 lowest amounts of sales. 6 */ 7 8 public class SalesData 9 { 10 private double[] sales; // The sales data field 11 12 /** 13 The constructor copies the elements in 14 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 24 for (int index= 0; index < s.length; index++)
sales[index] = s[index]; } 27 /** getTotal method @return The total of the elements in the sales array. */ 33 public double getTotal() { double total = 0; 37 // Accumulate the sum of values in the sales array.

25 40 for (int index = 0; index < sales.length; index++)
total += sales[index]; 42 43 44 return total; 45 } 46 47 /** 48 getAverage method 49 @return The average of the elements 50 in the sales array. 51 */ 52 53 public double getAverage() 54 { 55 return getTotal() / sales.length; 56 } 57 58 /** 59 getHighest method 60 @return The highest value stored 61 in the sales array. 62 */ (Continued)

26 63 64 public double getHighest() 65 { 66 double highest = sales[0]; 67 68 for (int index = 1; index < sales.length; index++) 69 { if (sales[index] > highest) highest = sales[index]; 72 } 73 return highest; 75 } 76 77 /** getLowest method @return The lowest value stored in the sales array. 81 */ 82 (Continued)

27 83 public double getLowest()
84 { double lowest = sales[0]; 86 for (int index = 1; index < sales.length; index++) { if (sales[index] < lowest) lowest = sales[index]; } 92 return lowest; 94 } 95 }

28 Code Listing 7-11 (Sales.java)
1 import javax.swing.JOptionPane; 2 import java.text.DecimalFormat; 3 4 /** 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 */ 9 10 public class Sales 11 { 12 public static void main(String[] args) 13 { 14 final int ONE_WEEK = 7; 15 17 double[] sales = new double[ONE_WEEK]; 18 20 getValues(sales); 21 (Continued)

29 22 // Create a SalesData object.
24 SalesData week = new SalesData(sales); 25 27 DecimalFormat dollar = new DecimalFormat("#,##0.00"); 28 // Display the total, average, highest, and lowest // sales amounts for the week. 31 JOptionPane.showMessageDialog(null, "The total sales were $" + dollar.format( week.getTotal() ) + "\nThe average sales were $" + dollar.format( week.getAverage() ) + "\nThe highest sales were $" + dollar.format( week.getHighest() ) + "\nThe lowest sales were $" + dollar.format( week.getLowest() )); 40 System.exit(0); 42 } // end main() 43 (Continued)

30 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 // Get sales for each day of the week. 55 for (int i = 0; i < array.length; i++) 56 { input = JOptionPane.showInputDialog("Enter " + "the sales for day " + (i + 1) + "."); array[i] = Double.parseDouble(input); } 61 } 62 } // end class

31 Code Listing 7-12 (Grader.java)
1 /** 2 The Grader class calculates the average 3 of an array of test scores, with the 4 lowest score dropped. 5 */ 6 7 public class Grader 8 { private double[] testScores; 13 /** Constructor @param scoreArray An array of test scores. */ 18 19 public Grader( double[] scoreArray ) 20 { (Continued)

32 22 21 // Assign the array argument to data field.
23 testScores = scoreArray; // What is stored in “testscores”? 24 } // end constructor 26 /** 27 getLowestScore method 28 @return The lowest test score. 29 */ 30 31 public double getLowestScore() 32 { 33 double lowest; 34 36 lowest = testScores[0]; // Why is “testscores” usable? 37 39 41 for (int index = 1; index < testScores.length; index++) 42 { if (testScores[index] < lowest) (Continued)

33 44 lowest = testScores[index];
45 } 46 47 // Return the lowest test score. 48 return lowest; 49 } 51 /** 52 getAverage method 53 @return The average of the test scores 54 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 62 63 65 66 if (testScores.length < 2) (Continued)

34 67 { System.out.println("ERROR: You must have at " + "least two test scores!"); average = 0; 71 } 72 else 73 { 74 for (double score : testScores) // Enhanced for-loop total += score; 77 78 lowest = getLowestScore(); 80 // Subtract the lowest score from the total.) total -= lowest; 83 // Get the adjusted average. average = total / (testScores.length - 1); 86 } 87 88 89 return average; 90 } // end method 91 } // end class

35 Code Listing 7-13 (CalcAverage.java)
1 import java.util.Scanner; 2 3 /** 4 This program gets a set of test scores and 5 uses the Grader class to calculate the average 6 with the lowest score dropped. 7 */ 8 9 public class CalcAverage 10 { 11 public static void main(String[] args) 12 { 13 int numScores; // To hold the number of scores 14 16 Scanner keyboard = new Scanner(System.in); 17 System.out.print("How many test scores do you have? "); 20 numScores = keyboard.nextInt(); 21 (Continued)

36 // Create an array to hold the test scores.
23 double[] scores = new double[numScores]; 24 25 // Get the test scores and store them. 27 for (int index = 0; index < numScores; index++ ) 28 { System.out.print("Enter score #" + (index + 1) + ": "); scores[index] = keyboard.nextDouble(); 32 } 33 37 Grader myGrader = new Grader( scores ); 38 40 System.out.println("Your adjusted average is " + myGrader.getAverage()); 42 (Continued)

37 Program Output with Example Input Shown in Bold
// Display the lowest score. 44 System.out.println("Your lowest test score was " + myGrader.getLowestScore()); 46 47 } } 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.0 Your lowest test score was 40.0

38 Code Listing 7-14 (ReturnArray.java)
1 /** 2 This program demonstrates how a reference to an 3 array can be returned from a method. 4 */ 5 6 public class ReturnArray 7 { 8 public static void main(String[] args) 9 { double[] values; 11 12 values = getArray(); for (double num : values) System.out.print(num + " "); 15 } 16 17 /** 18 getArray method 19 @return A reference to an array of doubles. 20 */ 21 (Continued)

39 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

40 Code Listing 7-15 (MonthDays.java)
1 /** 2 This program demonstrates an array of String objects. 3 */ 4 5 public class MonthDays 6 { 7 public static void main(String[] args) 8 { String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; 13 int[] days = { 31, 28, 31, 30, 31, 30, 31, , 30, 31, 30, 31 }; 16 for (int index = 0; index < months.length; index++) { System.out.println( months[index] + " has " + days[index] + " days."); } } 23 } (Continued)

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

42 Code Listing 7-16 (ObjectArray.java)
1 import java.util.Scanner; 3 /** 4 This program works with an array of three 5 BankAccount objects. 6 */ 7 8 public class ObjectArray 9 { 10 public static void main(String[] args) 11 { final int NUM_ACCOUNTS = 3; 13 // Create an array of BankAccount objects. BankAccount[] accounts = new BankAccount[NUM_ACCOUNTS]; 17 createAccounts(accounts); 20 21 System.out.println("Here are the balances " + "for each account:"); (Continued)

43 24 25 for (int index = 0; index < accounts.length; index++) 26 { System.out.println("Account " + (index + 1) + ": $" + accounts[index].getBalance() ); 29 } 30 } 31 32 /** 33 The createAccounts method creates a BankAccount 34 object for each element of an array. The user 35 Is asked for each account's balance. 36 @param array The array to reference the accounts 37 */ 38 39 private static void createAccounts(BankAccount[] array) 40 { 41 double balance; 42 43 44 Scanner keyboard = new Scanner(System.in); 45 (Continued)

44 // Create the accounts. 47 for (int index = 0; index < array.length; index++) { 49 System.out.print("Enter the balance for " + "account " + (index + 1) + ": "); balance = keyboard.nextDouble(); 53 54 array[index] = new BankAccount(balance); } 57 } } Program Output with Example Input Shown in Bold Enter the balance for account 1: [Enter] Enter the balance for account 2: [Enter] Enter the balance for account 3: [Enter] Here are the balances for each account: Account 1: $2500.0 Account 2: $5000.0 Account 3: $1500.0

45 Code Listing 7-17 (SearchArray.java)
1 /** 2 This program sequentially searches an 3 int array for a specified value. 4 */ 5 6 public class SearchArray 7 { 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) { System.out.println("You did not " + "earn 100 on any test."); (Continued)

46 22 } 23 else 24 { System.out.println("You earned 100 " + "on test " + (results + 1)); 27 } 28 } // end main() 29 30 /** 31 The sequentialSearch method searches an array for 32 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 the 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)

47 Program Output You earned 100 on test 4
46 47 index = 0; 48 50 element = -1; 51 found = false; 52 53 // Search the array. 54 while (!found && index < array.length) 55 { if (array[index] == value) // FOUND IT! { found = true; element = index; // HERE! } index++; 62 } 63 64 return element; // What are possible return values? 65 } // end search 66 } // end class Program Output You earned 100 on test 4

48 Code Listing 7-18 (CorpSales.java)
1 import java.util.Scanner; 2 3 /** 4 This program demonstrates a two-dimensional array. 5 */ 6 7 public class CorpSales 8 { 9 public static void main(String[] args) 10 { 11 final int DIVS = 3; // Three divisions in the company 12 final int QTRS = 4; // Four quarters 13 double totalSales = 0.0; 14 15 16 double[][] sales = new double[DIVS][QTRS]; 18 19 20 Scanner keyboard = new Scanner(System.in); 21 (Continued)

49 23 System.out.println("This program will calculate the " +
"total sales of"); 25 System.out.println("all the company's divisions. " ); 26 27 28 // Nested loops. WHY! 30 for (int div = 0; div < DIVS; div++ ) 31 { for (int qtr = 0; qtr < QTRS; qtr++ ) { System.out.printf("Division %d, Quarter %d: $", (div + 1), (qtr + 1)); sales[div][qtr] = keyboard.nextDouble(); } System.out.println(); 39 } 40 // Nested loops to add all the elements of the array.

50 for ( int div = 0; div < DIVS; div++ )
{ for ( int qtr = 0; qtr < QTRS; qtr++ ) { totalSales += sales[div][qtr]; } 48 } 49 // Display the total sales. 51 System.out.printf("Total company sales: $%,.2f\n", totalSales); 53 } 54 } Program Output with Example Input Shown in Bold This program will calculate the total sales of all the company's divisions. Enter the following sales data: Division 1, Quarter 1: $ [Enter] Division 1, Quarter 2: $ [Enter] Division 1, Quarter 3: $ [Enter] Division 1, Quarter 4: $ [Enter] (Continued)

51 Division 2, Quarter 1: $ 41289.64 [Enter]
Total company sales: $419,262.72

52 Code Listing 7-19 (Lengths.java)
1 /** 2 This program uses the length fields of a 2D array 3 to display the number of rows, and the number of 4 columns in each row. 5 */ 6 7 public class Lengths 8 { 9 public static void main(String[] args) 10 { 11 13 14 int[][] numbers = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; // What is size of the array? 17 19 System.out.println("The number of " + "rows is " + numbers.length ); 21

53 The number of columns in row 0 is 4
// Display the number of columns in each row. 23 for (int index = 0; index < numbers.length; index++) 24 { System.out.println("The number of " + "columns in row " + index + " is " + numbers[index].length ); 28 } 29 } 30 } Program Output The number of rows is 3 The number of columns in row 0 is 4 The number of columns in row 1 is 4 The number of columns in row 2 is 4

54 Code Listing 7-20 (Pass2Darray.java)
1 /** 2 This program demonstrates methods that accept 3 a two-dimensional array as an argument. 4 */ 5 6 public class Pass2Darray 7 { 8 public static void main(String[] args) 9 { 10 int[][] numbers = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; 13 15 System.out.println("Here are the values " + " in the array."); 17 showArray(numbers); 18 20 System.out.println("The sum of the values " + "is " + arraySum(numbers)); 22 } (Continued)

55 31 { 23 24 /** 25 The showArray method displays the contents
24 /** 25 The showArray method displays the contents 26 of a two-dimensional int array. 27 @param array The array to display. 28 */ 29 30 private static void showArray(int[][] array) 31 { for (int row = 0; row < array.length; row++ ) { for (int col = 0; col < array[row].length; col++ ) System.out.print( array[row][col] + " “ ); System.out.println(); } } 39 40 /** 41 The arraySum method returns the sum of the 42 values in a two-dimensional int array. 43 @param array The array to sum. 44 @return The sum of the array elements. 45 */ (Continued)

56 51 for (int row = 0; row < array.length; row++ ) 52 {
46 47 private static int arraySum(int[][] array) 48 { 49 int total = 0; 50 51 for (int row = 0; row < array.length; row++ ) 52 { for (int col = 0; col < array[row].length; col++ ) total += array[row][col]; 55 } 56 57 return total; 58 } } // End class Program Output Here are the values in the array. The sum of the values is 78

57 Code Listing 7-21 (CommandLine.java)
1 /** 2 This program displays the arguments passed to 3 it from the operating system command line. 4 */ 5 6 public class CommandLine 7 { 8 public static void main( String[] args ) 9 { for (int index = 0; index < args.length; index++) System.out.println( args[index] ); 12 } 13 }

58 total = totalBalance(account1);
Code Listing 7-22 (VarargsDemo2.java) 1 /** 2 This program demonstrates a method that accepts 3 a variable number of arguments (varargs). 4 */ 5 6 public class VarargsDemo2 7 { 8 public static void main(String[] args) 9 { 10 double total; 11 12 13 BankAccount account1 = new BankAccount(100.0); 14 15 16 BankAccount account2 = new BankAccount(500.0); 17 18 19 BankAccount account3 = new BankAccount(1500.0); 20 21 total = totalBalance(account1); 23 System.out.println("Total: $" + total); (Continued)

59 25 26 total = totalBalance(account1, account2); 27 System.out.println("Total: $" + total); 28 29 30 total = totalBalance(account1, account2, account3); 31 System.out.println("Total: $" + total); 32 } 33 34 /** 35 The totalBalance method takes a variable number 36 of BankAccount objects and returns the total 37 of their balances. 38 @param accounts The target account or accounts. 39 @return The sum of the account balances 40 */ 41 42 public static double totalBalance(BankAccount... accounts) 43 { 44 double total = 0.0; // What is “accounts” ?

60 Program Output Total: $100.0 Total: $600.0 Total: $2100.0 45 46
47 for (BankAccount acctObject : accounts) total += acctObject.getBalance(); 49 // Return the total. 51 return total; 52 } } Program Output Total: $100.0 Total: $600.0 Total: $2100.0

61 Code Listing 7-23 (ArrayListDemo1.java)
1 import java.util.ArrayList; 2 3 /** 4 This program demonstrates an ArrayList. 5 */ 6 7 public class ArrayListDemo1 8 { 9 public static void main(String[] args) 10 { 11 12 ArrayList<String> nameList = new ArrayList<String>(); 13 14 15 nameList.add("James"); 16 nameList.add("Catherine"); 17 nameList.add("Bill"); 18 19 System.out.println("The ArrayList has " + nameList.size() + " objects stored in it."); (Continued)

62 The ArrayList has 3 objects stored in it. James Catherine Bill
23 // Now display the items in nameList. for (int index = 0; index < nameList.size(); index++) System.out.println(nameList.get(index)); 27 } 28 } Program Output The ArrayList has 3 objects stored in it. James Catherine Bill

63 Code Listing 7-24 (ArrayListDemo2.java)
1 import java.util.ArrayList; 2 3 /** 4 This program demonstrates how the enhanced for loop 5 can be used with an ArrayList. 6 */ 7 8 public class ArrayListDemo2 9 { 10 public static void main(String[] args) 11 { 12 13 ArrayList<String> nameList = new ArrayList<String>(); 14 15 16 nameList.add("James"); 17 nameList.add("Catherine"); 18 nameList.add("Bill"); 19 20 System.out.println("The ArrayList has " + nameList.size() + " objects stored in it."); (Continued)

64 The ArrayList has 3 objects stored in it. James Catherine Bill
24 25 // Now display the items in nameList. 26 for (String name : nameList) System.out.println(name); 28 } 29 } Program Output The ArrayList has 3 objects stored in it. James Catherine Bill

65 Code Listing 7-25 (ArrayListDemo3.java)
1 import java.util.ArrayList; 2 3 /** 4 This program demonstrates an ArrayList. 5 */ 6 7 public class ArrayListDemo3 8 { 9 public static void main(String[] args) 10 { 11 ArrayList<String> nameList = new ArrayList<String>(); 13 14 nameList.add("James"); nameList.add("Catherine"); nameList.add("Bill"); 18 19 for (int index = 0; index < nameList.size(); index++) { System.out.println("Index: " + index + " Name: " + nameList.get(index)); }

66 The item at index 1 is removed. Here are the items now.
26 // Now remove the item at index 1. 27 nameList.remove(1); 28 29 System.out.println("The item at index 1 is removed. " + "Here are the items now.“ ); 31 32 33 for (int index = 0; index < nameList.size(); index++) 34 { System.out.println("Index: " + index + " Name: " + nameList.get(index)); 37 } 38 } } Program Output Index: 0 Name: James Index: 1 Name: Catherine Index: 2 Name: Bill The item at index 1 is removed. Here are the items now. Index: 1 Name: Bill

67 Code Listing 7-26 (ArrayListDemo4.java)
1 import java.util.ArrayList; // Needed for ArrayList class 2 3 /** 4 This program demonstrates inserting an item. 5 */ 6 7 public class ArrayListDemo4 8 { 9 public static void main(String[] args) 10 { 11 12 ArrayList<String> nameList = new ArrayList<String>(); 13 14 15 nameList.add("James"); 16 nameList.add("Catherine"); 17 nameList.add("Bill"); 18 19 20 for (int index = 0; index < nameList.size(); index++) 21 { (Continued)

68 for(index = 0; index < nameList.size(); index++) {
System.out.println("Index: " + index + " Name: " + nameList.get(index)); 24 } 25 // Now insert an item at index 1. 27 nameList.add(1, "Mary"); 28 29 System.out.println("Mary was added at index 1. " + "Here are the items now."); 31 32 33 for (int index = 0; index < nameList.size(); index++) 34 { System.out.println("Index: " + index + " Name: " + nameList.get(index)); 37 } 38 } 39 } (Continued)

69 Program Output Index: 0 Name: James Index: 1 Name: Catherine Index: 2 Name: Bill Mary was added at index 1. Here are the items now. Index: 1 Name: Mary Index: 2 Name: Catherine Index: 3 Name: Bill

70 Code Listing 7-27 (ArrayListDemo6.java)
1 import java.util.ArrayList; 2 3 /** 4 This program demonstrates how to store BankAccount 5 objects in an ArrayList. 6 */ 7 8 public class ArrayListDemo6 9 { 10 public static void main(String[] args) 11 { 12 13 ArrayList<BankAccount> list = new ArrayList<BankAccount>(); 14 // 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)

71 Program Output Account at index 0 Balance: 100.0 Account at index 1
20 // Display each item. 21 for (int index = 0; index < list.size(); index++) 22 { BankAccount account = list.get(index); System.out.println("Account at index " + index + "\nBalance: " + account.getBalance()); 26 } 27 } 28 Program Output Account at index 0 Balance: 100.0 Account at index 1 Balance: 500.0 Account at index 2 Balance:


Download ppt "Starting Out with Java: From Control Structures through Objects"

Similar presentations


Ads by Google