Starting Out with Java: From Control Structures through Objects 5th

advertisement
Starting Out with Java:
From Control Structures
through Objects
5th edition
By Tony Gaddis
Source Code: Chapter 5
Code Listing 5-1 (SimpleMethod.java)
1
/**
2 This program defines and calls a simple method.
3 */
5 public
6 {
class SimpleMethod
7 public static void
8 {
9
10
11
12 }
14
main(String[] args)
System.out.println("Hello from the main method.");
displayMessage();
System.out.println("Back in the main method.");
18 public static void displayMessage()
19 {
20
21 }
22 }
System.out.println("Hello from the displayMessage method.");
Program Output
Hello from the main method.
Hello from the displayMessage method.
Back in the main method.
Code Listing 5-2 (LoopCall.java)
1 /**
2
3
4
5
6
7
8
9
10
11
This program defines and calls a simple method.
*/
public class LoopCall
{
public static void main(String[] args)
{
System.out.println("Hello from the main method.");
for (int i = 0; i < 5; i++)
displayMessage();
12
System.out.println("Back in the main method.");
13 }
14
15
18
19 public static void displayMessage()
20 {
21
System.out.println("Hello from the displayMessage method.");
22 }
23 }
Program Output
Hello from the main method.
Hello from the displayMessage method.
Hello from the displayMessage method.
Hello from the displayMessage method.
Hello from the displayMessage method.
Hello from the displayMessage method.
Back in the main method.
Code Listing 5-3 (CreditCard.java)
1 import javax.swing.JOptionPane;
3 /**
4
This program uses two void methods.
5 */
6
7 public class CreditCard
8 {
9
public static void main(String[] args)
10 {
11
double salary;
// Annual salary
12
int
creditRating; // Credit rating
13
String input;
// To hold the user’s input
14
15 // Get the user’s annual salary.
16
17
18
input = JOptionPane.showInputDialog(“What is " +
"your annual salary?");
salary = Double.parseDouble(input);
(Continued)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Get the user’s credit rating (1 through 10).
input = JOptionPane.showInputDialog(“On a scale of " +
"1 through 10, what is your credit rating?\n" +
"(10 = excellent, 1 = very bad)");
creditRating = Integer.parseInt(input);
// Determine whether the user qualifies.
if (salary >= 20000 && creditRating >= 7)
qualify();
else
noQualify();
System.exit(0);
}
/**
The qualify method informs the user that he
or she qualifies for the credit card.
*/
(Continued)
39
40
41
42
43
44
45
46
47
48
49
50
public static void qualify()
{
JOptionPane.showMessageDialog(null, "Congratulations! " +
"You qualify for the credit card!");
}
/**
The noQualify method informs the user that he
or she does not qualify for the credit card.
*/
51 public static void noQualify()
52 {
53
JOptionPane.showMessageDialog(null, "I'm sorry. You " +
54
"do not qualify for the credit card.");
55 }
56 }
Code Listing 5-4 (DeepAndDeeper.java)
1
2
3
4
5
6
/**
This program demonstrates hierarchical method calls.
*/
public class DeepAndDeeper
{
7 public static void main(String[] args)
8 {
9
System.out.println("I am starting in main.");
10
deep();
11
System.out.println("Now I am back in main.");
12 }
13
14 /**
15
The deep method displays a message and then calls
16
the deeper method.
17 */
18
(Continued)
19 public static void deep()
20 {
21
System.out.println("I am now in deep.");
22
deeper();
23
System.out.println("Now I am back in deep.");
24 }
25
26 /**
27
The deeper method simply displays a message.
28 */
29
30 public static void deeper()
31 {
32
System.out.println("I am now in deeper.");
33 }
34 }
Program Output
I am starting in main.
I am now in deep.
I am now in deeper.
Now I am back in deep.
Now I am back in main.
Code Listing 5-5 (PassArg.java)
1 /**
2 This program demonstrates a method with a parameter.
3 */
4
5 public class PassArg
6 {
7
8
public static void main(String[] args)
{
9
int x = 10;
10
11 System.out.println("I am passing values to displayValue.");
12
13
14
displayValue(5);
displayValue(x);
displayValue( x * 4 );
displayValue( Integer.parseInt( "700") );
15
16
System.out.println("Now I am back in main.");
17 }
18
19 /**
20
The displayValue method displays the value
21
of its integer parameter.
22 */
(Continued)
23
24 public static void displayValue( int num )
25 {
26
System.out.println("The value is " + num);
27 }
28 }
Program Output
I am passing values to displayValue.
The value is 5
The value is 10
The value is 40
The value is 700
Now I am back in main.
Code Listing 5-6 (PassByValue.java)
1 /**
2
This program demonstrates that only a copy of an argument
3
is passed into a method.
4 */
5
6 public class PassByValue
7 {
8
public static void main(String[] args)
9
{
10
int number = 99;
11
12
13
System.out.println("number is " + number);
14
15
// Call changeMe, passing the value in number
16
// as an argument.
17
18
19
20
21
22
changeMe(number);
// Display the value in number again.
System.out.println("number is " + number);
}
(Continued)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 }
/**
The changeMe method accepts an argument and then
changes the value of the parameter.
*/
public static void changeMe( int myValue )
{
System.out.println("I am changing the value.");
myValue = 0;
// Display the value in myValue.
System.out.println("Now the value is " + myValue);
}
Program Output
number is 99
I am changing the value.
Now the value is 0
number is 99
Code Listing 5-7 (PassString.java)
1 /**
2 This program demonstrates that String arguments
3 cannot be changed.
4 */
5
6 public class PassString
7 {
8 public static void main(String[] args)
9 {
10
// Create a String object containing "Shakespeare".
11
// The name variable references the object.
12
13
14
15
16
17
18
19
20
21
String name = "Shakespeare";
// Display the String referenced by the name variable.
System.out.println("In main, the name is " +
name);
// Call the changeName method, passing the
// contents of the name variable as an argument.
changeName(name);
(Continued)
22
23
// Display the String referenced by the name variable.
System.out.println("Back in main, the name
name);
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 }
is " +
}
// END MAIN
/**
The changeName method accepts a String as its argument
and assigns the str parameter to a new String.
*/
public static void changeName( String str )
{
// Create a String object containing "Dickens".
// Assign its address to the str parameter variable.
str = "Dickens";
// Display the String referenced by str.
System.out.println("In changeName,
the name " +
"is now " + str);
}
Program Output
In main, the name is Shakespeare
In changeName, the name is now Dickens
Back in main, the name is Shakespeare
Code Listing 5-8 (LocalVars.java)
1
2
3
4
5
6
7
8
/**
This program demonstrates that two methods may have
local variables with the same name.
*/
9
{
public class LocalVars
{
public static void main(String[] args)
texas();
california();
10
11
12
13
14
15
16
17
18
19
20
21
}
/**
The texas method has a local variable named birds.
*/
public static void texas()
{
int birds = 5000;
(Continued)
22
23
24
25
26
27
28
System.out.println("In texas there are " +
birds + " birds.");
} // END TEXAS
/**
The california method also has a local variable named birds.
*/
29 public static void california()
30 {
31
int birds = 3500;
32
33
System.out.println("In california there are " +
34
birds + " birds.");
35 }
36 } // END CLASs
Program Output
In texas there are 5000 birds.
In california there are 3500 birds.
Code Listing 5-9 (ValueReturn.java)
1 /**
2 This program demonstrates a value-returning method.
3 */
4
5 public class ValueReturn
6 {
7 public static void main(String[] args)
8
{
9
10
11
12
13
int total, value1 = 20, value2 = 40;
14
15
16
17
18
19
20
21
total = sum(value1, value2);
// Call the sum method, passing the contents of
// value1 and value2 as arguments. Assign the
// return value to the total variable.
// Display the contents of all these variables.
System.out.println("The sum of " + value1 +
" and " + value2 + " is " +
total);
}
22 /**
23
The sum method returns the sum of its two parameters.
24
@param num1 The first number to be added.
25
@param num2 The second number to be added.
26
27 */
28
@return The sum of num1 and num2.
29 public static int sum(
30 {
int num1, int num2 )
31
32
33
int result;
34
35
36
result = num1 + num2;
37
// Assign the value of num1 + num2 to result.
// Return the value in the result variable.
return result;
38 }
39 }
Program Output
The sum of 20 and 40 is 60
Code Listing 5-10 (CupConverter.java)
1 import javax.swing.JOptionPane;
2
3 /**
4
This program converts cups to fluid ounces.
5 */
6
7 public class CupConverter
8 {
9
public static void main(String[] args)
10 {
11
double cups;
// To hold the number of cups
12
double ounces;
// To hold the number of ounces
13
14
15
cups = getCups();
16
17
18
ounces = cupsToOunces( cups );
19
20
21
displayResults( cups, ounces );
22 System.exit(0);
23 } // End main
(Continued)
24
25 /**
26
The getCups method prompts the user to enter a number
27
of cups.
28
@return The number of cups entered by the user.
29 */
30
31 public static double getCups()
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{
String input;
double numCups;
// To hold input.
// To hold cups.
// Get the number of cups from the user.
input = JOptionPane.showInputDialog(
"This program converts measurements\n" +
"in cups to fluid ounces. For your\n" +
"reference the formula is:\n" +
" 1 cup = 8 fluid ounces\n\n" +
"Enter the number of cups.");
// Convert the input to a double.
numCups = Double.parseDouble(input);
(Continued)
47
// Return the number of cups.
48 return numCups;
49
50
51
52
53
54
55
56
57
58
59
} // End GetCups
60
61
{
62
63
64
65
66
}
/**
The cupsToOunces method converts a number of
cups to fluid ounces, using the formula
1 cup = 8 fluid ounces.
@param numCups The number of cups to convert.
@return The number of ounces.
*/
public static double cupsToOunces( double numCups )
return numCups * 8.0;
/**
The displayResults method displays a message showing
the results of the conversion.
(Continued)
67
68
69
70
71
@param cups A number of cups.
@param ounces A number of ounces.
*/
public static void displayResults( double cups, double ounces )
72
73
74
75
76
{
77
78 }
}
// Display the number of ounces.
JOptionPane.showMessageDialog(null,
cups + " cups equals " +
ounces + " fluid ounces.");
Code Listing 5-11 (ReturnString.java)
1
2
3
4
5
6
7
/**
This program demonstrates a method that
returns a reference to a String object.
*/
public class ReturnString
{
8 public static void main(String[] args)
9
{
String customerName;
10
11
12
customerName = fullName( "John", "Martin“ );
13
System.out.println(customerName);
14
15
}
(Continued)
16
17
18
19
20
21
22
23
24
25
26
/**
27
28
29
30
31
{
32
33 }
}
The fullName method accepts two String arguments
containing a first and last name. It concatenates
them into a single String object.
@param first The first name.
@param last The last name.
@return A reference to a String object containing
the first and last names.
*/
public static String fullName( String first, String last )
String name;
name = first + " " + last;
return name;
Program Output
John Martin
Code Listing 5-12 (SalesReport.java)
1
2
3
4
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
// For the Scanner class
// For file I/O classes
// For the DecimalFormat class
// For the JOptionPane class
5
6 /**
7
8
9
This program opens a file containing the sales
amounts for 30 days. It calculates and displays
the total sales and average daily sales.
10 */
11
12 public
13 {
class SalesReport
14
public static void main(String[] args) throws
15
16
17
18
19
20
21
22
{
23
final int NUM_DAYS = 30;
String filename;
double totalSales;
double averageSales;
IOException
// Number of days of sales
// The name of the file to open
// Total sales for period
// Average daily sales
// Get the name of the file.
filename = getFileName();
(Continued)
23
24
// Get the total sales from the file.
25
26
totalSales = getTotalSales(filename);
28
29
averageSales = totalSales / NUM_DAYS;
31
32
33
34
35
36
37
38
39
40
41
42
43
displayResults( totalSales, averageSales );
44
System.exit(0);
} // End Main
/**
The getFileName method prompts the user to enter
the name of the file to open.
@return A reference to a String object containing
the name of the file.
*/
public static String getFileName()
{
(Continued)
45
46
47
48
49
50
51
52
53
String file;
54
55
56
57
return file;
58
59
60
61
62
63
64
65
// Prompt the user to enter a file name.
file = JOptionPane.showInputDialog("Enter " +
"the name of the file\n" +
"containing 30 days of " +
"sales amounts.");
// Return the name.
}
/**
The getTotalSales method opens a file and
reads the daily sales amounts, accumulating
the total. The total is returned.
@param filename The name of the file to open.
@return The total of the sales amounts.
*/
public static double getTotalSales( String filename ) throwIOException
67
68
69
70
71
{
double total = 0.0;
double sales;
// Accumulator
// A daily sales amount
// Open the file.
72
File file = new File(filename);
73
74
75
76
Scanner inputFile = new Scanner(file);
// This loop processes the lines read from the file,
// until the end of the file is encountered.
77
while ( inputFile.hasNext() )
78
79
{
// Read a double from the file.
80
81
82
sales = inputFile.nextDouble();
83
total += sales;
84
85
86
87
// Add sales to the value already in total.
}
// Close the file.
inputFile.close();
89
90
// Return the total sales.
return total;
91 } // END getTotalSales
92
93 /**
94
The displayResults method displays the total and
95
average daily sales.
96
@param total The total sales.
97
@param avg The average daily sales.
98 */
99
100
public static void displayResults(
101
102
103
104
105
106
107
108
109
110
{
111
}
112 }
double total, double avg )
// Create a DecimalFormat object capable of formatting
// a dollar amount.
DecimalFormat dollar = new DecimalFormat("#,###.00");
// Display the total and average sales.
JOptionPane.showMessageDialog(null, "The total sales for " +
"the period is $" + dollar.format(total) +
"\nThe average daily sales were $" +
dollar.format(avg));
Download