300 likes | 490 Vues
Starting Out with Java: From Control Structures through Objects 5 th 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 SimpleMethod 6 {
E N D
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 SimpleMethod 6 { 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 Output Hello 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 */ 4 5 public class LoopCall 6 { 7 public static void main(String[] args) 8 { • System.out.println("Hello from the main method."); 10 for (inti = 0; i < 5; i++) 11displayMessage(); 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 intcreditRating; // Credit rating 13 String input; // To hold the user’s input 14 • // Get the user’s annual salary. 16 input = JOptionPane.showInputDialog(“What is " + 17 "your annual salary?"); 18 salary = Double.parseDouble(input); (Continued)
19 • // 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); 25 • // Determine whether the user qualifies. 27 if (salary >= 20000 && creditRating >= 7) 28 qualify(); 29 else 30 noQualify(); 31 32 System.exit(0); 33 } 34 35 /** 36 The qualify method informs the user that he 37 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 } 45 46 /** 47 The noQualify method informs the user that he 48 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 DeepAndDeeper 6 { 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 public static void main(String[] args) 8 { 9 int x = 10; 10 • System.out.println("I am passing values to displayValue."); • displayValue(5); • displayValue(x); 14 displayValue( x * 4 ); 15 displayValue( Integer.parseInt( "700") ); 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( intnum ) 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 intnumber = 99; 11 12 13 System.out.println("number is " + number); 14 15 // Call changeMe, passing the value in number • // as an argument. 17 changeMe(number); 18 • // 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 then 25 changes the value of the parameter. 26 */ 27 28 public static void changeMe( intmyValue ) 29 { 30 System.out.println("I am changing the value."); 31 32 33 myValue = 0; 34 35 // Display the value in myValue. 36 System.out.println("Now the value is " + myValue); 37 } 38 } 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". • // The name variable references the object. 12 String name = "Shakespeare"; 13 14 // Display the String referenced by the name variable. 15 System.out.println("In main, the name is " + 16 name); 17 18 // Call the changeName method, passing the • // contents of the name variable as an argument. 20 changeName(name); 21 (Continued)
22 // Display the String referenced by the name variable. 23 System.out.println("Back in main, the name is " + 24 name); 25 } // END MAIN 26 27 /** 28 The changeName method accepts a String as its argument 29 and assigns the str parameter to a new String. 30 */ 31 32 public static void changeName( String str ) 33 { 34 // Create a String object containing "Dickens". • // Assign its address to the str parameter variable. 36 str = "Dickens"; 37 38 // Display the String referenced by str. 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 have 3 local variables with the same name. 4 */ 5 6 public class LocalVars 7 { 8 public static void main(String[] args) 9 { 10 texas(); 11 california(); 12 } 13 14 /** 15 The texas method has a local variable named birds. 16 */ 17 18 public static void texas() 19 { 20 intbirds = 5000; 21 (Continued)
22 System.out.println("In texas there are " + 23 birds + " birds."); 24 } // END TEXAS 25 26 /** 27 The california method also has a local variable named birds. 28 */ 29 public static void california() 30 { 31 intbirds = 3500; 32 33 System.out.println("In california there are " + 34 birds + " birds."); 35 } 36 } // END CLASs Program Output Intexas 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 int total, value1 = 20, value2 = 40; 10 11 // Call the sum method, passing the contents of 12 // value1 and value2 as arguments. Assign the • // return value to the total variable. 14 total = sum(value1, value2); 15 16 // Display the contents of all these variables. 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 intsum( int num1, int num2 ) 30 { 31 int result; 32 33 // Assign the value of num1 + num2 to result. 34 result = num1 + num2; 35 36 // 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; 2 3 /** 4 This program converts cups to fluid ounces. 5 */ 6 7 public class CupConverter 8 { 9 public static voidmain(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 ); • 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 String input; // To hold input. 34 double numCups; // To hold cups. 35 36 // 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."); 43 44 // Convert the input to a double. 45 numCups = Double.parseDouble(input); (Continued)
47 // Return the number of cups. • returnnumCups; 49 } // End GetCups 50 51 /** 52 The cupsToOuncesmethod converts a number of 53 cups to fluid ounces, using the formula 54 1 cup = 8 fluid ounces. 55 @paramnumCups The number of cups to convert. 56 @return The number of ounces. 57 */ 58 59 public static double cupsToOunces( double numCups ) 60 { 61 return numCups * 8.0; 62 } 63 64 /** 65 The displayResults method displays a message showing 66 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 // Display the number of ounces. 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 arguments 18 containing a first and last name. It concatenates 19 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 containing 23 the first and last names. 24 */ 25 26 public static String fullName( String first, String last ) 27 { 28 String name; 29 30 name = first + " " + last; 31 return name; 32 } 33 } Program Output John Martin
Code Listing 5-12 (SalesReport.java) 1import java.util.Scanner; // For the Scanner class 2 import java.io.*; // For file I/O classes 3 import java.text.DecimalFormat; // For the DecimalFormat class 4 import javax.swing.JOptionPane; // For the JOptionPane class 5 6 /** 7This program opens a file containing the sales 8 amounts for 30 days. It calculates and displays 9 the total sales and average daily sales. 10 */ 11 12 public class SalesReport 13 { 14 public static void main(String[] args) throws IOException 15 { 16 final int NUM_DAYS = 30; // Number of days of sales 17 String filename; // The name of the file to open 18 double totalSales; // Total sales for period 19 double averageSales; // Average daily sales 20 • // Get the name of the file. • filename = getFileName(); (Continued)
23 • // Get the total sales from the file. 25 totalSales = getTotalSales(filename); 26 28 averageSales = totalSales / NUM_DAYS; 29 31 displayResults( totalSales, averageSales ); 32 33 System.exit(0); 34 } //End Main 35 36 /** 37 The getFileName method prompts the user to enter 38 the name of the file to open. 39 @return A reference to a String object containing 40 the name of the file. 41 */ 42 43 public static String getFileName() 44 { (Continued)
45 String file; 46 47 // Prompt the user to enter a file name. 48 file =JOptionPane.showInputDialog("Enter " + 49 "the name of the file\n" + 50 "containing 30 days of " + 51 "sales amounts."); 52 53 // Return the name. 54 return file; 55 } 56 57 /** 58 The getTotalSales method opens a file and 59 reads the daily sales amounts, accumulating 60 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 65 public static double getTotalSales( String filename ) throwIOException
67 { 68 double total = 0.0; // Accumulator 69 double sales; // A daily sales amount 70 • // Open the file. 72 File file = new File(filename); 73 Scanner inputFile = new Scanner(file); 74 75 // 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 sales = inputFile.nextDouble(); 81 82 // Add sales to the value already in total. 83 total += sales; 84 } 85 • // Close the file. 87 inputFile.close(); 88 (Continued)
89 // Return the total sales. 90 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 @paramavg The average daily sales. 98 */ 99 100 public static void displayResults( double total, double avg ) 101 { 102 // Create a DecimalFormat object capable of formatting 103 // a dollar amount. 104 DecimalFormat dollar = new DecimalFormat("#,###.00"); 105 106 // Display the total and average sales. 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 }