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

Slides:



Advertisements
Similar presentations
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
1 Fall 2009ACS-1903 Methods – Ch 5 A design technique referred to as stepwise refinement (or divide and conquer, or functional decomposition) is used to.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Chapter 3b Standard Input and Output Sample Development.
Scanner & Stepwise Refinement Pepper With credit to Dr. Siegfried.
Computer Programming Lab(4).
JOptionPane class. Dialog Boxes A dialog box is a small graphical window that displays a message to the user or requests input. A variety of dialog boxes.
Starting Out with Java: From Control Structures through Objects
Starting Out with Java: From Control Structures through Objects
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Input/Output in Java. Output To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples.
Chapter The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number.
Programming Fundamentals 2: Simple/ F II Objectives – –give some simple examples of Java applications and one applet 2. Simple Java.
9/20: The while Repetition Structure last time’s program repetition structures: what they are the while repetition structure homework due on Thursday program.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
DT249-Information Systems Research Practice Programming Revision Lecture 2 Lecturer: Patrick Browne.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Methods Chapter Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
1/28: Inputs, Variable Types, etc. Addition.java in depth Variable types & data types Input from user: how to get it Arithmetic operators.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
Dialog Boxes.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
2/18: Assignment Operators About Average2.java –while loop use –explicit casting –twoDigits object Assignment Operators Increment & Decrement Operators.
Ihsan Ayyub Qazi Introduction to Computer Programming Recitation 3 Ihsan Ayyub Qazi.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 9.
1 Class Chapter Objectives Use a while loop to repeat a series of statements Get data from user through an input dialog box Add error checking.
Computer Programming1 Computer Science 1 Computer Programming.
Files Review For output to a file: –FileOutputStream variable initialized to filename (String) and append/not append (boolean) –PrintWriter variable initialized.
Chapter 5 : Methods. Why Write Methods?  Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
Chapter 5 : Methods Part 2. Returning a Value from a Method  Data can be passed into a method by way of the parameter variables. Data may also be returned.
Method Examples CS 139 Algorithm Development 10/06/2008.
Exam Review 10/01/2014 Happy October. The Exam  Will be in Canvas  Two parts  Part A is recall – closed book, closed notes ◦Quizzes, in class activity.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
UFCFY5-30-1Multimedia Studio Coding for Interactive Media Fundamental Concepts.
Chapter 5 Methods. 2 Contents 1. Introduction to Methods 2. Passing Arguments to a Method 3. More about Local Variables 4. Returning a Value from a Method.
Starting Out with C++: From Control Structures through Objects
Chapter 2 Clarifications
Introduction to programming in java
Chapter 7 User-Defined Methods.
2.5 Another Java Application: Adding Integers
by Tony Gaddis and Godfrey Muganda
Dialogues and Wrapper Classes
Starting Out with Java: From Control Structures through Objects
Methods.
if-else-if Statements
Chapter Topics Chapter 5 discusses the following main topics:
Starting Out with Java: From Control Structures through Objects
Starting Out with Java: From Control Structures through Objects
Chapter 4: Loops and Files
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Starting Out with Java: From Control Structures through Objects
Happy October Exam Review 10/01/2014.
JOptionPane class.
F II 2. Simple Java Programs Objectives
Chapter 4: Loops and Files
Chapter 2: Java Fundamentals cont’d
Presentation transcript:

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 { 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 } 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 { 9System.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 } 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. 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 input = JOptionPane.showInputDialog(“What is " + 17 "your annual salary?"); 18 salary = Double.parseDouble(input); (Continued)

19 20// 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 26// Determine whether the user qualifies. 27 if (salary >= && creditRating >= 7) 28 qualify(); 29 else 30 noQualify(); System.exit(0); 33 } /** 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 } /** 47 The noQualify method informs the user that he 48 or she does not qualify for the credit card. 49 */ 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 } /** 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 } /** 27 The deeper method simply displays a message. 28 */ 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 11System.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 } /** 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; System.out.println("number is " + number); // Call changeMe, passing the value in number 16 // as an argument. 17 changeMe(number); 18 19// 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 */ public static void changeMe ( int myValue ) 29 { 30 System.out.println("I am changing the value."); myValue = 0; // 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". 11 // The name variable references the object. 12 String name = "Shakespeare"; // Display the String referenced by the name variable. 15 System.out.println(" In main, the name is " + 16 name); // Call the changeName method, passing the 19 // 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 /** 28 The changeName method accepts a String as its argument 29 and assigns the str parameter to a new String. 30 */ public static void changeName ( String str ) 33 { 34 // Create a String object containing "Dickens". 35 // Assign its address to the str parameter variable. 36 str = "Dickens"; // 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 } /** 15 The texas method has a local variable named birds. 16 */ 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 /** 27 The california method also has a local variable named birds. 28 */ 29 public static void california() 30 { 31 int birds = 3500; 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 int total, value1 = 20, value2 = 40; // Call the sum method, passing the contents of 12 // value1 and value2 as arguments. Assign the 13 // return value to the total variable. 14 total = sum(value1, value2); // Display the contents of all these variables. 17 System.out.println("The sum of " + value " and " + value2 + " is " + 19 total); 20 } 21 (Continued)

22 /** 23 The sum method returns the sum of its two parameters. num1 The first number to be added. num2 The second number to be added. The sum of num1 and num2. 27 */ public static int sum( int num1, int num2 ) 30 { 31 int result; // Assign the value of num1 + num2 to result. 34 result = num1 + num2; // 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 void main ( String[] args) 10 { 11 double cups; // To hold the number of cups 12 double ounces; // To hold the number of ounces cups = getCups(); ounces = cupsToOunces( cups ); displayResults( cups, ounces ); 22System.exit(0); 23 } // End main (Continued)

24 25 /** 26 The getCups method prompts the user to enter a number 27 of cups. The number of cups entered by the user. 29 */ public static double getCups() 32 { 33 String input; // To hold input. 34 double numCups; // To hold cups // 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."); // Convert the input to a double. 45 numCups = Double.parseDouble(input); (Continued)

47 // Return the number of cups. 48return numCups; 49 } // End GetCups /** 52 The cupsToOunces method converts a number of 53 cups to fluid ounces, using the formula 54 1 cup = 8 fluid ounces. numCups The number of cups to convert. The number of ounces. 57 */ public static double cupsToOunces ( double numCups ) 60 { 61 return numCups * 8.0; 62 } /** 65 The displayResults method displays a message showing 66 the results of the conversion. (Continued)

cups A number of cups. ounces A number of ounces. 69 */ 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; 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. first The first name. last The last name. A reference to a String object containing 23 the first and last names. 24 */ public static String fullName ( String first, String last ) 27 { 28 String name; name = first + " " + last; 31 return name; 32 } 33 } Program Output John Martin

Code Listing 5-12 (SalesReport.java) 1 import 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 /** 7 This 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 */ 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 // Get the name of the file filename = getFileName(); (Continued)

23 24// Get the total sales from the file. 25 totalSales = getTotalSales(filename); averageSales = totalSales / NUM_DAYS; displayResults( totalSales, averageSales ); System.exit(0); 34 } // End Main /** 37 The getFileName method prompts the user to enter 38 the name of the file to open. A reference to a String object containing 40 the name of the file. 41 */ public static String getFileName() 44 { (Continued)

45 String file; // 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."); // Return the name. 54 return file; 55 } /** 58 The getTotalSales method opens a file and 59 reads the daily sales amounts, accumulating 60 the total. The total is returned. filename The name of the file to open. The total of the sales amounts. 63 */ public static double getTotalSales ( String filename ) throwIOException

67 { 68 double total = 0.0; // Accumulator 69 double sales; // A daily sales amount 70 71// Open the file. 72 File file = new File(filename); 73 Scanner i nputFile = new Scanner( file ); // This loop processes the lines read from the file, 76// until the end of the file is encountered. 77 while ( inputFile.hasNext() ) 78 { 79 // Read a double from the file. 80 sales = inputFile.nextDouble(); // Add sales to the value already in total. 83 total += sales; 84 } 85 86// Close the file. 87 inputFile.close(); 88 (Continued)

89 // Return the total sales. 90 return total; 91 } // END getTotalSales /** 94 The displayResults method displays the total and 95 average daily sales. total The total sales. avg The average daily sales. 98 */ 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"); // Display the total and average sales. 107 JOptionPane.showMessageDialog(null, "The total sales for " "the period is $" + dollar.format(total) "\nThe average daily sales were $" dollar.format(avg)); 111 } 112 }