Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Class Methods.

Slides:



Advertisements
Similar presentations
The 3 rd and 4 th tutoring session -- A case study about using variables Fall, 2012 Haidong(Haydon) Xue 5:30pm8:30pm 9/11/2012 and 9/12/2012.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
Introduction to Computers and Programming Introduction to Methods in Java.
Java: How to Program Methods Summary Yingcai Xiao.
Introduction to Computer Programming Looping Around Loops I: Counting Loops.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Introduction to Computer Programming Loops N Decisions If/Else Counting Loops.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Chapter 7: User-Defined Methods
Lecture 7. Review Homework 1 (sample solution) Project 1 will be assigned next week –Draw a picture (whatever you want) in the world by using turtles.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING 1 Chapter 2 Writing Java Programs.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
CPS 2231 Computer Organization and Programming Instructor: Tian (Tina) Tian.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 5 Loops.
CSc2310 tutoring session, week 8 Fall, 2012 Haidong(Haydon) Xue 5:30pm—8:30pm 11/27/2012 and 11/28/2012 -Class Members vs Instance Members.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
Building Java Programs Chapter 3 Parameters and Objects Copyright (c) Pearson All rights reserved.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
CSC Programming I Lecture 6 September 4, 2002.
Writing Static Methods Up until now, we have been USING (calling) static methods that other people have written. Now, we will start CREATING our own static.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
The 9 th and 10 th tutoring session Fall, 2012 Haidong Xue 5:30pm—8:30pm 10/2/2012 and 10/3/2012 -Review loop structures and improve CheckISBN and CourseAverage.
Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 7 Class.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
Class Variables and Methods
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CS305j Introduction to Computing Parameters and Methods 1 Topic 8 Parameters and Methods "We're flooding people with information. We need to feed it through.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC111 Quick Revision.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Strings (Continued) Chapter 13
Data Types and Conversions, Input from the Keyboard
Exceptions and User Input Validation
Yanal Alahmad Java Workshop Yanal Alahmad
More Control Structures
Computer Programming Methodology Input and While Loop
Methods.
Writing Java Programs Chapter 2
Static and non-Static Chapter 5.
Control Statement Examples
Java Fix a program that has if Online time for Monday’s Program
Chapter 4: Mathematical Functions, Characters, and Strings
Writing Java Programs Chapter 2
CHAPTER 6 GENERAL-PURPOSE METHODS
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
Writing Java Programs Chapter 2
Introduction to Computer Programming
Java Fix a program that has if Online time for Monday’s Program
Writing Java Programs Chapter 2
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
Writing Java Programs Chapter 2
Classes CS 21a: Introduction to Computing I
Random Numbers while loop
Writing Java Programs Chapter 2
Ch 5 : Mathematical Functions, Characters, and Strings
Presentation transcript:

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Class Methods

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Class Methods Versus Instance Methods Review from Chapter 3: –A Java program consists of classes. –Most classes contain both instance variables and instance methods. –Any object created from a class will have its own copy of the class ’ s instance variables, and that object will be capable of calling the class ’ s (public) instance methods. Examples of classes: –Account –String (part of the Java API)

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 3 Instance Method Review An instance method may access the instance variables in an object without changing them, or it may modify instance variables. If acct is an Account variable, the call acct.deposit( ); deposits $1000 into the Account object that acct represents. If str contains a String object, the length method can be used to find the length of the string: int len = str.length();

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 4 Class Methods Not all methods require access to instance variables. For example, a method that computes the square root of a number has nothing to do with objects. Methods that don ’ t need access to instance variables are known as class methods (or static methods.) A class method—like all methods in Java—must belong to a class.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 5 Class Methods If a class method has been declared public, it can be called as follows: class. method-name ( arguments ) When a class method is called by another method in the same class, the class name and dot can be omitted.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 6 Class Methods Class methods used in Chapter 2: Double.parseDouble Integer.parseInt Math.abs Math.max Math.min Math.pow Math.round Math.sqrt

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 7 Class Methods Some uses of class methods: –To provide a service to other classes. Methods in this category are declared public. –To help other methods in the same class. “ Helper ” methods provide assistance to other methods in the same class. Helper methods should be private.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Writing Class Methods Writing a class method is similar to writing an instance method, except that the declaration of a class method must contain the word static. Parts of a class method declaration: –Access modifier –The word static –Result type –Method name –Parameters –Body

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 9 Declaring Class Methods Example of a class method declaration:

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 10 Parameters for Class Methods Java requires that main ’ s result type be void and that main have one parameter of type String[] (array of String objects). Other class methods may have any number of parameters, including none. If a method has more than one parameter, each parameter except the last must be followed by a comma.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 11 Access Modifiers for Class Methods Java requires that the main method be declared public. Other class methods can be declared either public or private. Class methods that are intended for use by other classes should be declared public. Class methods that are intended for use within a single class should be declared private. A private method can be modified without having to worry about how the changes might affect other classes.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Writing Helper Methods Instead of putting all the code for a program into main, it ’ s better to delegate some of its duties to helper methods. In general, a helper method is any method whose job is to assist another method, not necessarily main. A helper for a class method such as main must be another class method, because class methods aren't allowed to call instance methods in the same class. Instance methods can have helpers as well. A helper for an instance method can be either an instance method or a class method.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 13 Advantages of Using Helper Methods Helper methods have two primary advantages: –Greater clarity. The main method can be shortened, with helper methods taking care of details. –Less redundancy. A repeated segment of code can be moved into a method and then called as many times as needed. The CourseAverage program of Section 2.11 suffers from a great deal of repetitive code. By moving this code to class methods, the program can be made shorter, as well as more understandable and easier to modify.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 14 Improving Clarity The original design of CourseAverage : 1. Print the introductory message ( “ Welcome to the CSc 2310 average calculation program ” ). 2. Prompt the user to enter eight program scores. 3. Compute the program average from the eight scores. 4. Prompt the user to enter five quiz scores. 5. Compute the quiz average from the five scores. 6. Prompt the user to enter scores on the tests and final exam. 7. Compute the course average from the program average, quiz average, test scores, and final exam score. 8. Round the course average to the nearest integer and display it.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 15 The Revised CourseAverage Program The revised CourseAverage program has three class methods: readProgramScores, readQuizScores, and readDouble. Other changes to the program: –Class variables are used as constants. –Loops are used to read the program scores and grades. –The readDouble method is used to help read the test scores and the final exam score.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 16 CourseAverage2.java // Program name: CourseAverage2 // Author: K. N. King // Written: // Modified: // // Prompts the user to enter eight program scores (0-20), five // quiz scores (0-10), two test scores (0-100), and a final // exam score (0-100). Scores may contain digits after the // decimal point. Input is not checked for validity. Displays // the course average, computed using the following formula: // // Programs 30% // Quizzes 10% // Test 1 15% // Test 2 15% // Final exam 30% // // The course average is rounded to the nearest integer.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 17 import java.util.Scanner; public class CourseAverage2 { // Constants private static final int NUM_PROGRAMS = 8; private static final int NUM_QUIZZES = 5; private static final int MAX_PROG_SCORE = 20; private static final int MAX_QUIZ_SCORE = 10; private static final double PROGRAM_WEIGHT =.30; private static final double QUIZ_WEIGHT =.10; private static final double TEST_WEIGHT =.15; private static final double FINAL_EXAM_WEIGHT =.30; public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Print the introductory message System.out.println("Welcome to the CSc 2310 average " + "calculation program.\n");

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 18 // Prompt the user to enter program scores and compute // the average of the scores double programAverage = readProgramScores(sc) / NUM_PROGRAMS; // Leave a blank line System.out.println(); // Prompt the user to enter quiz scores and compute the // average of the scores double quizAverage = readQuizScores(sc) / NUM_QUIZZES; // Leave a blank line System.out.println(); // Prompt the user to enter scores on the tests and final // exam double test1 = readDouble(sc,"Enter Test 1 score: "); double test2 = readDouble(sc,"Enter Test 2 score: "); double finalExam = readDouble(sc,"Enter Final Exam score: ");

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 19 // Compute the course average from the program average, // quiz average, test scores, and final exam score double courseAverage = PROGRAM_WEIGHT * (programAverage / MAX_PROG_SCORE * 100) + QUIZ_WEIGHT * (quizAverage / MAX_QUIZ_SCORE * 100) + TEST_WEIGHT * test1 + TEST_WEIGHT * test2 + FINAL_EXAM_WEIGHT * finalExam; // Round the course average to the nearest integer and // display it System.out.println("\nCourse average: " + Math.round(courseAverage)); }

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 20 /////////////////////////////////////////////////////////// // NAME: readProgramScores // BEHAVIOR: Prompts the user to enter program scores // and computes their total. // PARAMETERS: None // RETURNS: Total of program scores /////////////////////////////////////////////////////////// private static double readProgramScores(Scanner sc) { double programTotal = 0.0; for (int i = 1; i <= NUM_PROGRAMS; i++) programTotal += readDouble(sc,"Enter Program " + i + " score: "); return programTotal; }

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 21 /////////////////////////////////////////////////////////// // NAME: readQuizScores // BEHAVIOR: Prompts the user to enter quiz scores and // computes their total. // PARAMETERS: None // RETURNS: Total of quiz scores /////////////////////////////////////////////////////////// private static double readQuizScores(Scanner sc) { double quizTotal = 0.0; for (int i = 1; i <= NUM_QUIZZES; i++) quizTotal += readDouble(sc,"Enter Quiz " + i + " score: "); return quizTotal; }

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 22 /////////////////////////////////////////////////////////// // NAME: readDouble // BEHAVIOR: Prompts the user to enter a number, reads // the user's input, and converts it to double // form. // PARAMETERS: prompt - the prompt to be displayed // RETURNS: User's input after conversion to double /////////////////////////////////////////////////////////// private static double readDouble(Scanner sc, String prompt) { System.out.print(prompt); String userInput = sc.nextLine(); return Double.parseDouble(userInput); }