Starting Out with Java: From Control Structures through Objects

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.
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.
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.
Chapter The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number.
 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.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
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.
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.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 5.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
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
CSC111 Quick Revision.
Introduction to programming in java
Chapter 7 User-Defined Methods.
Exercise 1- I/O Write a Java program to input a value for mile and convert it to kilogram. 1 mile = 1.6 kg. import java.util.Scanner; public class MileToKg.
Exceptions and User Input Validation
CSC305: COMPUTER PROGRAMMING II (JAVA)
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
Computer Programming Methodology Input and While Loop
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
Lecture 5- Classes, Objects and Methods
Chapter 4 - Control Structures: Part 1
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.
Exception Handling Contents
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 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 (int i = 0; i < 5; i++) 11 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. 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 // Get the user’s annual salary. 16 input = JOptionPane.showInputDialog(“What is " + 17 "your annual salary?"); 18 salary = Double.parseDouble(input); (Continued)

// Get the user’s credit rating (1 through 10). 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)

40 public static void qualify() 41 { 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)

Program Output 19 public static void deep() 20 { 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( 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 // 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( int myValue ) 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

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)

Program Output In main, the name is Shakespeare 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 int birds = 5000; 21 (Continued)

In texas there are 5000 birds. In california there are 3500 birds. 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 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 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)

Program Output The sum of 20 and 40 is 60 22 /** 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; 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 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 ); 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)

return numCups; 47 // Return the number of cups. 49 } // End GetCups 50 51 /** 52 The cupsToOunces method converts a number of 53 cups to fluid ounces, using the formula 54 1 cup = 8 fluid ounces. 55 @param numCups 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)

Program Output John Martin 16 /** 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

filename = getFileName(); 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 */ 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 // Calculate the average. 28 averageSales = totalSales / NUM_DAYS; 29 // Display the total and average. 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 @param avg 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 }