Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis
description
Transcript of Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis
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 class SimpleMethod6 {
7 public static void main(String[] args)
8 {9 System.out.println("Hello from the main method.");
10 displayMessage();11 System.out.println("Back in the main method.");
12 }14
18 public static void displayMessage()19 {20 System.out.println("Hello from the displayMessage method.");
21 }22 }
Program OutputHello from the main method.Hello from the displayMessage method.Back in the main method.
Code Listing 5-2 (LoopCall.java)1 /**2 This program defines and calls a simple method.3 */45 public class LoopCall6 {7 public static void main(String[] args)8 {9 System.out.println("Hello from the main method.");
10 for (int i = 0; i < 5; i++)11 displayMessage();
12 System.out.println("Back in the main method.");13 }1415 1819 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 */67 public class CreditCard8 {9 public static void main(String[] args)10 {11 double salary; // Annual salary12 int creditRating; // Credit rating13 String input; // To hold the user’s input1415 // Get the user’s annual salary.
16 input = JOptionPane.showInputDialog(“What is " +17 "your annual salary?");18 salary = Double.parseDouble(input);
(Continued)
1920 // Get the user’s credit rating (1 through 10).
21 input = JOptionPane.showInputDialog(“On a scale of " +22 "1 through 10, what is your credit rating?\n" +23 "(10 = excellent, 1 = very bad)");24 creditRating = Integer.parseInt(input);2526 // Determine whether the user qualifies.
27 if (salary >= 20000 && creditRating >= 7)28 qualify();29 else30 noQualify();3132 System.exit(0);33 }3435 /**36 The qualify method informs the user that he37 or she qualifies for the credit card.38 */
(Continued)
39
40 public static void qualify()41 {42 JOptionPane.showMessageDialog(null, "Congratulations! " +43 "You qualify for the credit
card!");44 }4546 /**47 The noQualify method informs the user that he48 or she does not qualify for the credit card.49 */50
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 This program demonstrates hierarchical method calls.3 */4
5 public class DeepAndDeeper6 {
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 }1314 /**15 The deep method displays a message and then calls16 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 }2526 /**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 OutputI 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 Call-By-Value technique for invoking a method.3 */4
5 public class PassArg6 {
7 public static void main(String[] args)
8 {
9 int x = 10;1011 System.out.println("I am passing values to displayValue.");
12 displayValue(5); 13 displayValue(x); 14 displayValue( x * 4 ); 15 displayValue( Integer.parseInt( "700") ); 16 System.out.println("Now I am back in main.");17 }1819 /**20 The displayValue method displays the value21 of its integer parameter.22 */
(Continued)
2324 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 5The value is 10The value is 40The value is 700Now I am back in main.
Code Listing 5-6 (PassByValue.java)1 /**2 This program demonstrates that only a copy of an argument3 is passed into a method.4 */56 public class PassByValue7 {8 public static void main(String[] args)9 {10 int number = 99; 1112 13 System.out.println("number is " + number);14
17 changeMe(number);1819 // Display the value in number again.
20 System.out.println("number is " + number);21 }22
(Continued)
23 /**24 The changeMe method accepts an argument and then25 changes the value of the parameter.26 */27
28 public static void changeMe( int myValue )29 {30 System.out.println("I am changing the value.");3132
33 myValue = 0;3435 // Display the value in myValue.36 System.out.println("Now the value is " + myValue);37 }38 }
Program Outputnumber is 99I am changing the value.Now the value is 0number is 99
Code Listing 5-7 (PassString.java)1 /**2 This program demonstrates that String arguments3 cannot be changed.4 */56 public class PassString7 {
8 public static void main(String[] args)9 {10 // Create a String object containing "Shakespeare".11
12 String name = "Shakespeare";1314
15 System.out.println("In main, the name is " +16 name);17
20 changeName(name);21
(Continued)
22
23 System.out.println("Back in main, the name is " +24 name);
25 } // END MAIN
31
32 public static void changeName( String str )33 {34 // Create a String object containing "Dickens".35
36 str = "Dickens";3738
39 System.out.println("In changeName, the name " +40 "is now " + str);41 }42 }
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 This program demonstrates that two methods may have3 local variables with the same name.4 */5
6 public class LocalVars7 {
8 public static void main(String[] args)
9 {10 texas();11 california();12 }1314 /**15 The texas method has a local variable named birds.16 */17
18 public static void texas()19 {
20 int birds = 5000;21
(Continued)
22 System.out.println("In texas there are " +23 birds + " birds.");24 } // END TEXAS
29 public static void california()30 {
31 int birds = 3500;
3233 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 */45 public class ValueReturn6 {
7 public static void main(String[] args)
8 {9 int total, value1 = 20, value2 = 40;1011 // Call the sum method, passing the contents of12 // value1 and value2 as arguments. Assign the13 // return value to the total variable.
14 total = sum(value1, value2);1516 17 System.out.println("The sum of " + value1 +18 " and " + value2 + " is " +19 total);20 }21
(Continued)
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 @return The sum of num1 and num2.27 */28
29 public static int sum( int num1, int num2 )30 {
31 int result;
3233 // Assign the value of num1 + num2 to result.
34 result = num1 + num2;3536 // Return the value in the result variable.
37 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;23 /**4 This program converts cups to fluid ounces.5 */67 public class CupConverter8 {9 public static void main(String[] args)10 {11 double cups; // To hold the number of cups12 double ounces; // To hold the number of ounces1314 15 cups = getCups();1618 ounces = cupsToOunces( cups );1921 displayResults( cups, ounces );
22 System.exit(0);
23 } // End main(Continued)
2425 /**26 The getCups method prompts the user to enter a number27 of cups.
28 @return The number of cups entered by the user.29 */30
31 public static double getCups()32 {33 String input; // To hold input.34 double numCups; // To hold cups.3536 // Get the number of cups from the user.37 input = JOptionPane.showInputDialog(38 "This program converts measurements\n" +39 "in cups to fluid ounces. For your\n" +40 "reference the formula is:\n" +41 " 1 cup = 8 fluid ounces\n\n" +42 "Enter the number of cups.");4344 45 numCups = Double.parseDouble(input);
(Continued)
48 return numCups;
49 } // End GetCups5051 /**52 The cupsToOunces method converts a number of53 cups to fluid ounces, using the formula54 1 cup = 8 fluid ounces.55 @param numCups The number of cups to convert.56 @return The number of ounces.57 */5859 public static double cupsToOunces( double numCups )
60 {61 return numCups * 8.0;62 }6364 /**65 The displayResults method displays a message showing66 the results of the conversion.
(Continued)
67 @param cups A number of cups.68 @param ounces A number of ounces.69 */70
71 public static void displayResults( double cups, double ounces )
72 {73 74 JOptionPane.showMessageDialog(null,75 cups + " cups equals " +76 ounces + " fluid ounces.");
77 }78 }
Code Listing 5-11 (ReturnString.java)1 /**2 This program demonstrates a method that
3 returns a reference to a String object.4 */5
6 public class ReturnString
7 {8 public static void main(String[] args)
9 {10 String customerName;11
12 customerName = fullName( "John", "Martin“ );
13 System.out.println(customerName);
14 }15
(Continued)
16 /**17 The fullName method accepts two String arguments18 containing a first and last name. It concatenates19 them into a single String object.20 @param first The first name.21 @param last The last name.22 @return A reference to a String object containing23 the first and last names.24 */2526 public static String fullName( String first, String last )
27 {28 String name;2930 name = first + " " + last;31 return name;32 }33 }Program OutputJohn Martin
Code Listing 5-12 (SalesReport.java)1 import java.util.Scanner; // For the Scanner class2 import java.io.*; // For file I/O classes3 import java.text.DecimalFormat; // For the DecimalFormat class4 import javax.swing.JOptionPane; // For the JOptionPane class56 /**7 This program opens a file containing the sales8 amounts for 30 days. It calculates and displays9 the total sales and average daily sales.10 */11
12 public class SalesReport13 {14 public static void main(String[] args) throws IOException15 {16 final int NUM_DAYS = 30; // Number of days of sales17 String filename; // The name of the file to open18 double totalSales; // Total sales for period19 double averageSales; // Average daily sales2021 22
(Continued)
24 filename = getFileName();
25 totalSales = getTotalSales(filename);26
28 averageSales = totalSales / NUM_DAYS;29
31 displayResults( totalSales, averageSales );
32
33 System.exit(0);
34 } // End Main
3536 /**37 The getFileName method prompts the user to enter38 the name of the file to open.39 @return A reference to a String object containing40 the name of the file.41 */42
(Continued)
43 public static string getFileName()44 {45 String file; 4647
48 file = JOptionPane.showInputDialog("Enter " +49 "the name of the file\n" +50 "containing 30 days of " +51 "sales amounts.");5253
54 return file;55 }5657 /**
58 The getTotalSales method opens a file and59 reads the daily sales amounts, accumulating60 the total. The total is returned.61 @param filename The name of the file to open.62 @return The total of the sales amounts.63 */64
66 public static double getTotalSales(String filename) throws IOException
67 {68 double total = 0.0; // Accumulator
69 double sales; // A daily sales amount
70
72 File file = new File(filename);73 Scanner inputFile = new Scanner(file);74
77 while ( inputFile.hasNext() )78 {
80 sales = inputFile.nextDouble();81
83 total += sales;
84 }85
87 inputFile.close();88
(Continued)
89 // Return the total sales.
90 return total;91 } // END getTotalSales9293 /**94 The displayResults method displays the total and95 average daily sales.96 @param total The total sales.97 @param avg The average daily sales.98 */99
100 public static void displayResults( double total, double avg )101 {102
104 DecimalFormat dollar = new DecimalFormat("#,###.00");105106 107 JOptionPane.showMessageDialog(null, "The total sales for " +
108 "the period is $" + dollar.format(total) +
109 "\nThe average daily sales were $" +
110 dollar.format(avg)); }111 }112 } // end Class