Download System.out.println - CS Course Webpages

Document related concepts
no text concepts found
Transcript
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 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 " +
19
EMPLOYEES + " employees.");
20
(Continued)
21
22
// Get the hours worked by employee 1.
System.out.print("Employee 1: ");
23
24
25
26
hours[0] = keyboard.nextInt();
27
28
29
30
hours[1] = keyboard.nextInt();
31
32
33
34
hours[2] = keyboard.nextInt();
35
36
37
// Get the hours worked by employee 2.
System.out.print("Employee 2: ");
// Get the hours worked by employee 3.
System.out.print("Employee 3: ");
// Display the values entered.
System.out.println("The hours you entered are:");
System.out.println(hours[0]);
System.out.println(hours[1]);
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:
40
20
15
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
8 {
class ArrayDemo2
9 public static void main(String[] args)
10 {
11 final int EMPLOYEES = 3;
12
13
14
15
16
17
// Number of employees
int[] hours = new int[EMPLOYEES];
// Array of hours
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the hours worked by " +
EMPLOYEES + " employees.");
18
19
20
// 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
28
29
System.out.println("The
30
for (int index = 0; index < EMPLOYEES; index++ )
System.out.println( hours[ index ] );
31
32 }
33 }
hours you entered are:");
// Display the values entered.
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
Code Listing 7-3 (InvalidSubscript.java)
1 /**
2 This program uses an invalid subscript with an array.
3 */
4
5 public
6 {
class InvalidSubscript
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 " +
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 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)
Code Listing 7-4 (ArrayInitialization.java)
1 /**
2 This program shows an array being
3 */
4
5 public class ArrayInitialization
6 {
7 public static void main(String[] args)
8 {
9
10
initialized.
int[] days = { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
11
12
for (int index = 0; index < 12; index++)
13
14
15
16
17
18 }
19 }
{
System.out.println("Month " + (index + 1) +
" has " + days[index] +
" days.");
}
// Valid subscripts in for-loop?
(Continued)
Program Output
Month 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 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 {
12
final int EMPLOYEES = 5;
13 double payRate;
14 double grossPay;
15
16
17
int[] hours = new int[EMPLOYEES];
18
19
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
30
{
System.out.print( "Employee #" + (index + 1) + ": ");
hours[index] = keyboard.nextInt();
31 }
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
40
41
42
43
44
for (int index = 0; index < EMPLOYEES; index++)
{
grossPay = hours[index] * payRate;
System.out.println("Employee #" + (index + 1) +
": $" + grossPay);
}
(Continued)
} // End main
46 } // End Class
45
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.
Code Listing 7-6 (DisplayTestScores.java)
1 import java.util.Scanner;
2
3 /**
4
This program demonstrates how the user may specify an
5 array's
6 */
7
8
// Needed for Scanner class
size.
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)
26
27
28
29
30
31
32
34
35
for (int index = 0; index < tests.length; index++)
{
System.out.print("Enter test score " +
(index + 1) + ": ");
tests[index] = keyboard.nextInt();
}
System.out.println();
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 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:
72 85 81 94 99
Code Listing 7-7 ( SameArray.java )
1 /**
2 This program demonstrates that two variables can
3 reference the same array.
4 */
5
6 public
7 {
8
9
10
11
12
class SameArray
public static void main(String[] args)
{
int[] array1 = { 2, 4, 6, 8, 10 };
int[] array2 = array1;
14
15
array1[0] = 200;
17
18
array2[4] = 1000;
20
System.out.println("The
21
22
contents of array1:");
for ( int value : arrayl )
System.out.print(value + " ");
23 System.out.println();
(Continued)
24
25
26
27
28
System.out.println("The contents of array2:");
for (int value : array2)
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 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
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
5 10 15 20 25 30 35 40
.length; index++)
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 " +
21
"numbers that you entered:");
(Continued)
22
23
24
showArray( numbers );
25 } // End main
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
The getValues method accepts a reference
to an array as its argument. The user is
asked to enter a value for each element.
@param array A reference to the array.
*/
private static void getValues( int[]
array )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a series of " +
.
array length + " numbers.“ );
41
(Continued)
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
.
for (int index = 0; index < array length; index++ )
{
System.out.print("Enter number " +
(index + 1) + ": ");
array[index] = keyboard.nextInt();
}
}
/**
The showArray method accepts an array as
an argument and displays its contents.
@param array A reference to the array.
*/
public
static void showArray(int[] array)
{
.
for (int index = 0; index < array length; index++ )
61
System.out.print( array[index] + " “ );
62 }
63 } // End Class
60
(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 /**
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.
2
6 */
7
8 public class SalesData
9 {
10 private double[] sales;
11
12 /**
13
14
15
16
sales data field
The constructor copies the elements in
an array to the sales array.
@param s The array to copy.
*/
17
18 public SalesData(double[]
19 {
20
21
22
// The
s)
sales = new double[ s.length ];
(Continued)
24
for (int index= 0; index < s.length; index++)
sales[index] = s[index];
25
26
}
27
28
/**
29
getTotal 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
for (int index = 0; index < sales.length; index++)
total += sales[index];
return total;
}
/**
getAverage method
@return The average of the elements
in the sales array.
*/
public double getAverage()
{
return getTotal() / sales.length;
}
/**
getHighest method
@return The highest value stored
in the sales array.
*/
(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
75 }
76
77 /**
78
79
80
81 */
82
return highest;
getLowest method
@return The lowest value stored
in the sales array.
(Continued)
83
84
public double getLowest()
{
85
86
double lowest = sales[0];
87
for (int index = 1; index < sales.length; index++)
88
{
if (sales[index] < lowest)
lowest = sales[index];
89
90
91
92
93
94 }
95 }
}
return lowest;
Code Listing 7-11 (Sales.java)
1 import javax.swing.JOptionPane;
2 import java.text.DecimalFormat;
3
4 /**
5
6
7
8
This program gathers sales amounts for the week.
It uses the SalesData class to display the total,
average, highest, and lowest sales amounts.
*/
9
10 public class Sales
11 {
12 public static void main(String[] args)
13 {
14
15
17
18
20
final int ONE_WEEK = 7;
double[] sales = new double[ONE_WEEK];
getValues(sales);
21
(Continued)
22
// Create a SalesData object.
24
25
27
28
29
30
SalesData week = new SalesData(sales);
31
32
33
34
35
36
37
38
39
40
41
JOptionPane.showMessageDialog(null,
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Display the total, average, highest, and lowest
// sales amounts for the week.
"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() ));
System.exit(0);
42 } // end main()
43
(Continued)
44
45
46
47
48
49
/**
The getValues method asks the user to enter sales
amounts for each element of an array.
@param array The array to store the values in.
*/
50
private static void getValues(double[]
51
{
array)
String input;
52
53
54
// Get sales for each day of the week.
55
for (int i = 0; i < array.length; i++)
56
{
input = JOptionPane.showInputDialog("Enter " +
57
"the sales for day " + (i + 1) + ".");
58
array[i] = Double.parseDouble(input);
59
60
61
62
}
}
} // end class
Code Listing 7-12 (Grader.java)
1
2
3
4
5
6
7
8
/**
The Grader class calculates the average
of an array of test scores, with the
lowest score dropped.
*/
public class Grader
{
12 private double[] testScores;
13
14 /**
15
Constructor
16
@param scoreArray An array of test scores.
17 */
18
19 public Grader( double[] scoreArray )
20 {
(Continued)
// Assign the array argument to data field.
21
22
testScores = scoreArray;
23
// What is stored in “testscores”?
24 } // end constructor
25----------------------------------------------------------------------------------------------------------------------------- ---26 /**
27 getLowestScore method
28 @return The lowest test score.
29 */
30
31 public double getLowestScore()
32
{
33
34
double lowest;
36
37
39
lowest = testScores[0];
41
for (int index = 1; index < testScores.length; index++)
42
{
43
// Why is “testscores” usable?
if (testScores[index] < lowest)
(Continued)
lowest = testScores[index];
44
45
46
47
}
48
return lowest;
// Return the lowest test score.
49 }
50----------------------------------------------------------------------------------------------------------------------------- ---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
60
61
62
63
65
66
double total = 0;
double lowest;
double average;
// To hold the score total
// To hold the lowest score
// To hold the average
if (testScores.length < 2)
(Continued)
67
68
69
{
System.out.println("ERROR: You must have at " +
"least two test scores!");
average = 0;
70
71
}
72
else
73
74
{
for (double score : testScores)
total += score;
75
76
77
78
// Enhanced for-loop
79
80
81
lowest = getLowestScore();
82
83
84
total -= lowest;
85
average = total / (testScores.length - 1);
86
87
88
// Subtract the lowest score from the total.)
// Get the adjusted average.
}
89 return average;
90 } // end method
91
} // end class
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
17
Scanner keyboard = new Scanner(System.in);
19
System.out.print("How many test scores do you have? ");
20
21
numScores = keyboard.nextInt();
(Continued)
22
// Create an array to hold the test scores.
23
24
25
26
double[] scores = new double[numScores];
27
28
29
30
31
32
33
for (int index = 0; index < numScores; index++ )
37
38
Grader myGrader = new Grader( scores );
40
System.out.println("Your adjusted average is " +
myGrader.getAverage());
41
42
// Get the test scores and store them.
{
System.out.print("Enter score #" +
(index + 1) + ": ");
scores[index] = keyboard.nextDouble();
}
(Continued)
43
44
45
46
47
48
// Display the lowest score.
System.out.println("Your lowest test score was " +
myGrader.getLowestScore());
}
}
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
Code Listing 7-14 (ReturnArray.java)
1
2
3
4
5
6
7
/**
This program demonstrates how a reference to an
array can be returned from a method.
*/
public class ReturnArray
{
8 public static void main(String[] args)
9
{
10 double[] values;
11
12
13
values = getArray();
for (double num : values)
System.out.print(num + " ");
14
15 }
16
17 /**
18 getArray method
19 @return A reference
20 */
21
to an array of doubles.
(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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
This program demonstrates an array of String objects.
*/
public class MonthDays
{
public static void main(String[] args)
{
String[] months = { "January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };
int[ ] days = { 31, 28, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31 };
for (int index = 0; index < months.length; index++)
{
System.out.println( months[index] + " has " +
days[index] + " days.");
}
18
19
20
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
3
4
5
6
7
8
9
import java.util.Scanner;
/**
This program works with an array
of three
BankAccount objects.
*/
public class ObjectArray
{
10
public static void
11
12
13
14
{
main(String[] args)
final int NUM_ACCOUNTS = 3;
// Create an array of BankAccount objects.
16
17
BankAccount[ ] accounts = new BankAccount[NUM_ACCOUNTS];
19
20
21
22
createAccounts(accounts);
23
System.out.println("Here are the balances " +
"for each account:");
(Continued)
24
25
26
27
28
for (int index = 0; index < accounts.length; index++)
{
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[
40 {
41 double balance;
42
43
44 Scanner keyboard = new Scanner(System.in);
45
] array)
(Continued)
46
47
48
49
50
51
52
53
54
55
56
57
58
// Create the accounts.
for (int index = 0; index < array.length; index++)
{
System.out.print("Enter the balance for " +
"account " + (index + 1) + ": ");
balance = keyboard.nextDouble();
array[index] = new BankAccount(balance);
}
}
}
Program Output with Example Input Shown in Bold
Enter 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.0
Account 2: $5000.0
Account 3: $1500.0
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
16
17
19
20
21
results = sequentialSearch(tests, 100);
if (results == -1)
{
System.out.println("You did not " +
"earn 100 on any test.");
(Continued)
22
}
23
else
24
{
System.out.println("You earned 100 " +
"on test " + (results + 1));
25
26
}
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
36
array, otherwise -1.
37 */
38
39
public static int sequentialSearch(int[ ] array, int value)
41 {
42
43
44
int index;
int element;
boolean found;
(Continued)
46
47
48
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
index = 0;
element = -1;
found = false;
// Search the array.
while (!found && index < array.length)
{
if (array[index] == value)
{
found = true;
element = index;
}
index++;
}
// FOUND IT!
// HERE!
return element;
65 } // end search
66 } // end class
Program Output
You earned 100 on test 4
// What are possible return values?
Code Listing 7-18 (CorpSales.java)
1 import java.util.Scanner;
2
3 /**
4 This program demonstrates
5 */
6
a two-dimensional array.
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
17
18
19
20
21
double[ ][ ] sales = new double[DIVS][QTRS];
Scanner keyboard = new Scanner(System.in);
(Continued)
23
System.out.println("This program will calculate the " +
24
"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
{
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
}
40
41 // 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
{
totalSales += sales[div][qtr];
46
}
47
48
49
}
50
// Display the total sales.
51
System.out.printf("Total company sales: $%,.2f\n",
52
53 }
54 }
totalSales);
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: $ 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 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
8 {
class Lengths
9 public static void
10 {
11
13
main(String[ ] args)
14 int[][] numbers = { { 1, 2, 3, 4 },
15
16
17
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } }; // What is size of the array?
19 System.out.println("The number of " +
20
21
"rows is " + numbers
.length );
22
// Display
the number of columns in each row.
23
24
for (int index = 0; index < numbers.length; index++)
{
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 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
.
Code Listing 7-20 (Pass2Darray.java)
1
2
3
/**
This program demonstrates methods that accept
a two-dimensional array as an argument.
4
5
6
*/
7
{
8
9
public class Pass2Darray
public static void main(String[] args)
{
int[ ][ ] numbers = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
10
11
12
13
System.out.println("Here are the values " +
" in the array.");
15
16
17
18
showArray(numbers);
20
System.out.println("The sum of the values " +
"is " + arraySum(numbers));
21
22
}
(Continued)
23
24
25
26
27
28
29
/**
The showArray method displays the contents
of a two-dimensional int array.
@param array The array to display.
*/
30
private static void showArray(int[
][ ] array)
31 {
32
for (int row = 0; row < array.length; row++ )
33
{
for (int col = 0; col < array[row].length; col++ )
34
System.out.print( array[row][col] + " “ );
35
System.out.println();
}
36
37
38
39
40
41
42
43
44
45
}
/**
The arraySum method returns the sum of the
values in a two-dimensional int array.
@param array The array to sum.
@return The sum of the array elements.
*/
(Continued)
46
47
private static int arraySum(int[ ][ ] array)
48
{
int total = 0;
49
50
51
52
53
for (int row = 0; row < array.length; row++ )
{
for (int col = 0; col < array[row].length; col++ )
total += array[row][col];
54
55
56
}
return total;
57
58
}
59 } // End class
----------------------------------------------------------------------------------------------------------Program Output
Here are the values in the array.
1234
5678
9 10 11 12
Code Listing 7-21 (CommandLine.java)
1
/**
This program displays the arguments passed to
it from the operating system command line.
2
3
4
5
*/
6
public class CommandLine
{
7
8
public static void
9
{
for (int index = 0; index < args.length; index++)
10
System.out.println( args[index] );
11
}
12
13
main( String[ ] args )
}
Code Listing 7-22 (VarargsDemo2.java)
1
2
/**
This program demonstrates a method that accepts
a variable number of arguments (varargs).
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
*/
public class VarargsDemo2
{
public static void main(String[ ] args)
{
double total;
BankAccount account1 = new BankAccount(100.0);
BankAccount account2 = new BankAccount(500.0);
BankAccount account3 = new BankAccount(1500.0);
22 total = totalBalance(account1);
23
System.out.println("Total: $" + total);
(Continued)
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
total = totalBalance(account1, account2);
System.out.println("Total: $" + total);
total = totalBalance(account1, account2, account3);
System.out.println("Total: $" + total);
}
/**
The totalBalance method takes a variable number
of BankAccount objects and returns the total
of their balances.
@param accounts The target account or accounts.
@return The sum of the account balances
*/
...
public static double totalBalance(BankAccount
accounts)
{
double total = 0.0;
// What is “accounts” ?
45
46
47
for (BankAccount acctObject : accounts)
48
total += acctObject.getBalance();
49
50
51
52
53
// Return the total.
return total;
}
}
Program Output
Total: $100.0
Total: $600.0
Total: $2100.0
Code Listing 7-23 (ArrayListDemo1.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.ArrayList;
/**
This program demonstrates an ArrayList.
*/
public class ArrayListDemo1
{
public static void main(String[ ] args)
{
ArrayList<String> nameList = new ArrayList<String>();
nameList.add("James");
nameList.add("Catherine");
nameList.add("Bill");
17
18
19 System.out.println("The ArrayList has " +
21
nameList.size() +
22
" objects stored in it.");
(Continued)
23
24
// Now
25
for (int index = 0; index < nameList.size(); index++)
26
27 }
28 }
display the items in nameList.
System.out.println(nameList.get(index));
Program Output
The ArrayList has 3 objects stored in it.
James
Catherine
Bill
Code Listing 7-24 (ArrayListDemo2.java)
1 import java.util.ArrayList;
2
3 /**
4 This program demonstrates how the enhanced
5 can be used with an ArrayList.
6 */
7
8 public
9{
for loop
class ArrayListDemo2
10 public static void main(String[] args)
11 {
12
13 ArrayList<String>
14
15
nameList = new ArrayList<String>();
16 nameList.add("James");
17 nameList.add("Catherine");
18 nameList.add("Bill");
19
20 System.out.println("The ArrayList has " +
22
nameList.size() +
" objects stored in it.");
(Continued)
24
25 //
Now display the items in nameList.
26 for
27
28 }
29 }
(String name : nameList)
System.out.println(name);
Program Output
The ArrayList has 3 objects stored in it.
James
Catherine
Bill
Code Listing 7-25 (ArrayListDemo3.java)
1
2
3
4
5
6
7
8
9
10
11
import java.util.ArrayList;
/**
This program demonstrates an ArrayList.
*/
public class ArrayListDemo3
{
public static void main(String[] args)
{
12
13
14
15
16
17
18
19
ArrayList<String> nameList = new ArrayList<String>();
20
for (int index = 0; index < nameList.size(); index++)
21
{
nameList.add("James");
nameList.add("Catherine");
nameList.add("Bill");
System.out.println("Index: " + index + " Name: " +
22
nameList.get(index));
23
24
}
26
// Now remove the item at index 1.
27
28
29
30
31
32
33
34
35
36
37
38 }
39 }
nameList.remove(1);
System.out.println("The item at index 1 is removed. " +
"Here are the items now.“ );
for (int index = 0; index < nameList.size(); index++)
{
System.out.println("Index: " + index + " Name: " +
nameList.get(index));
}
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: 0 Name: James
Index: 1 Name: Bill
Code Listing 7-26 (ArrayListDemo4.java)
1 import java.util.ArrayList;
2
3 /**
4 This program demonstrates
5 */
6
7 public class ArrayListDemo4
8 {
9
10
11
12
13
14
15
16
17
18
19
20
21
inserting an item.
public static void main(String[ ] args)
{
ArrayList<String> nameList = new ArrayList<String>();
nameList.add("James");
nameList.add("Catherine");
nameList.add("Bill");
for (int index = 0; index < nameList.size(); index++)
{
(Continued)
20
21
22
23
24
for(index = 0; index < nameList.size(); index++)
{
System.out.println("Index: " + index + " Name: " +
nameList.get(index));
}
25
26
// Now insert an item at index 1.
27
nameList.add(1, "Mary");
28
29
30
31
System.out.println("Mary was added at index 1. " +
"Here are the items now.");
32
33
34
35
36
37
38
39 }
for (int index = 0; index < nameList.size(); index++)
{
System.out.println("Index: " + index + " Name: " +
nameList.get(index));
}
}
(Continued)
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: 0 Name: James
Index: 1 Name: Mary
Index: 2 Name: Catherine
Index: 3 Name: Bill
Code Listing 7-27 (ArrayListDemo6.java)
1 import java.util.ArrayList;
2
3
/**
This program demonstrates how to store BankAccount
objects in an ArrayList.
4
5
6
7
*/
8
9
public class ArrayListDemo6
10
11
12
13
14
15
16
17
18
19
{
public static void
{
main(String[] args)
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
// Add three BankAccount objects to the ArrayList.
list.add(new BankAccount(100.0));
list.add(new BankAccount(500.0));
list.add(new BankAccount(1500.0));
(Continued)
20
21
22
23
24
25
26
27
28
// Display each item.
for (int index = 0; index < list.size(); index++)
{
BankAccount account = list.get(index);
System.out.println("Account at index " + index +
"\nBalance: " + account.getBalance());
}
}
Program Output
Account at index 0
Balance: 100.0
Account at index 1
Balance: 500.0
Account at index 2
Balance: 1500.0
Related documents