Helper Methods ITP © Ron Poet Lecture 11.

Slides:



Advertisements
Similar presentations
ITP © Ron Poet Lecture 4 1 Program Development. ITP © Ron Poet Lecture 4 2 Preparation Cannot just start programming, must prepare first. Decide what.
Advertisements

Building Java Programs
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Random (1) Random class contains a method to generate random numbers of integer and double type Note: before using Random class, you should add following.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
CS305j Introduction to Computing While Loops 1 Topic 15 Indefinite Loops - While Loops "If you cannot grok [understand] the overall structure of a program.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
ITP © Ron Poet Lecture 2 1 Mental Models. ITP © Ron Poet Lecture 2 2 Mental Models  A mental model is a way of making sense of something we experience.
ITP © Ron Poet Lecture 13 1 Helper Objects. ITP © Ron Poet Lecture 13 2 Console Helper Object  We have used Console objects for a while, let’s see what.
Methods and You. Up to this point, I have covered many different data types with you. Variables can be considered the nouns of an English sentence. If.
Methods. Topics Built-in methods Methods that return a value Void methods Programmer defined methods Scope Top Down Design.
ITP © Ron Poet Lecture 3 1 Comments. ITP © Ron Poet Lecture 3 2 Legibility  It is important that programs are easy to read.  It is easier to find bugs.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Chapter 5 Loops.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
ITIP © Ron Poet Lecture 12 1 Finding Out About Objects.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Procedural programming in Java Methods, parameters and return values.
Random numbers. 2 The Random class A Random object generates pseudo-random numbers. –Class Random is found in the java.util package. import java.util.*;
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Procedural Programming Criteria: P2 Task: 1.2 Thomas Jazwinski.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
ITIP © Ron Poet Lecture 14 1 Responsibilities. ITIP © Ron Poet Lecture 14 2 Two Sections of Code  If we ask two people to work together to do a job,
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
ITP © Ron Poet Lecture 5 1 Branching. ITP © Ron Poet Lecture 5 2 CookTime After Midnight  We want to improve our program so that we can cook meals after.
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.
ITP © Ron Poet Lecture 15 1 Helper Objects Again.
AP Java Java’s version of Repeat until.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Building Java Programs Chapter 4 Lecture 4-1: Scanner ; cumulative algorithms reading: 3.3 – 3.4, 4.2.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Building Java Programs
CSC111 Quick Revision.
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Suppose we want to print out the word MISSISSIPPI in big letters.
Java Course Review.
Chapter 6 More Conditionals and Loops
Building Java Programs
Chapter 5: Control Structures II
Repetition-Counter control Loop
Incrementing ITP © Ron Poet Lecture 8.
Counted Loops.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CHAPTER 6 GENERAL-PURPOSE METHODS
Building Java Programs
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Random Numbers while loop
Methods/Functions.
Building Java Programs
Presentation transcript:

Helper Methods ITP © Ron Poet Lecture 11

Splitting Up Complicated Code The program to run a series of guess games is quite complicated. We made the design easier by splitting it into two parts. The games sequence. An individual game. Helper methods let us write the code in two or more parts as well. ITP © Ron Poet Lecture 11

A Single Game We can write a helper method to play a single game. The main method can then use this helper method to run a series of games. We can test the single game method first. Then test the series when the single game code works. ITP © Ron Poet Lecture 11

Inputs Helper methods need inputs to get started. Play a game needs: A Console object to communicate with the user. A Random object to choose random numbers. This information is provided by the main method. Inputs are called parameters. ITP © Ron Poet Lecture 11

Outputs The play a game method must tell the main method how many guesses the user needed. This information is given back to the main method. main can use it to calculate the average number of guesses needed. ITP © Ron Poet Lecture 11

private static Helper methods are private. This means that they can only be called by main or another helper method. More about public and private later. The main method is static and so all helper methods must be static as well. More on static later. ITP © Ron Poet Lecture 11

The Play a Game Method private static int playGame(Console con, Random rand) { // choose a random number between 0 and 9 int num = Math.abs(rand.nextInt()) % 10; System.err.println(num); // for testing // variable to count number of attempts int count = 0; // loop until user gets it right for (;;) // break out loop ITP © Ron Poet Lecture 11

Play a Game (2) // get the user's guess con.print("Guess a number: "); int guess = con.readInt(); count++; // print how they did if (guess == num) { con.println("CORRECT!!!, you took " + count + " guesses"); return count; } else if (guess > num) con.println("Too high"); else con.println("Too low"); ITP © Ron Poet Lecture 11

Method Header Tells how the method will be used. private static int playGame(Console con, Random rand) The method name: playGame The parameters are like variable definitions (Console con, Random rand) The return type: int Visibility: private (more later) Lifetime: static (more later) The rest is the method body. ITP © Ron Poet Lecture 11

Parameters Parameters are inputs to the method. They are variables with initial values. main will provide these initial values. They can be used anywhere in the method. They come straight after the method name. playGame(Console con, Random rand) There are 2 inputs, a Console called con and a Random called rand. ITP © Ron Poet Lecture 11

Return Value In Java a method can only return one value. In this case we want to return an integer value. The number of guesses. The type of return value comes before the method name. int playGame ITP © Ron Poet Lecture 11

return Statement A return statement sends a value back to main. return count; The value returned must be the same type as that specified in the method header. There can be many return statements in a method. Control is transferred back to the calling method when a return is encountered. ITP © Ron Poet Lecture 11

Running a Method This is also called calling a method. main must give playGame the information it needs The two parameters con and rand. They must be given in the order that playGame expects them. main must deal with the value returned. The number of guesses. ITP © Ron Poet Lecture 11

Calling playGame // create helper objects Console con = new Console("Guess"); Random rand = new Random(); // remember total score and number of games int totalScore = 0, numGames = 0; for (;;) // repeat games loop { // call playGame helper method totalScore += playGame(con, rand); numGames++; ITP © Ron Poet Lecture 11

Calling playGame (2) // see if should go round again con.print("Do you want another go? "); String reply = con.readWord(); if (reply.equals("no")) break; } // print out average score double average = (double)totalScore / numGames; con.print("Thank you for playing, your average was"); // average needs precision con.println(String.format(“%6.2f”, average)); ITP © Ron Poet Lecture 11

Calling playGame explained Here is the line that calls playGame. totalScore += playGame(con, rand); The two parameters con and rand are helper objects. They are created in main. They are given to playGame to use. The int returned by playGame is used by adding it to totalScore. ITP © Ron Poet Lecture 11

Layout Of The Program Here is how the main and helper methods are written in the program. import FormatIO.*; import java.util.*; import java.lang.*; public class Ex3 { public static void main(String[] arg) { // body of main } private static int playGame(Console con, Random rand) // body of playGame } // end of class Ex3 ITP © Ron Poet Lecture 11

Drawing a Triangle This example aims to draw a triangle made of stars, as the sample output shows. ITP © Ron Poet Lecture 11

Overall Design Get number of rows from user Loop with i from 1 to number of rows Draw a row with i stars ITP © Ron Poet Lecture 11

Draw A Row Input: Console, number of stars in the row. Output: None. Loop for number of stars Draw a * Draw a newline. ITP © Ron Poet Lecture 11

drawRow Helper Method Header Name: drawRow Parameters (Console con, int nStars) Return type: void (no output). private static void drawRow(Console con, int nStars) { for (int i = 1; i <= nStars; i++) con.print("*"); con.println(); } ITP © Ron Poet Lecture 11

main Method public static void main(String[] arg) { // get info from user Console con = new Console("Triangle"); con.print("How many rows of stars?: "); int nRows = con.readInt(); // loop through rows for (int i = 1; i <= nRows; i++) drawRow(con, i); } ITP © Ron Poet Lecture 11

Things To Note The variable name i is used in both methods. It is the name of two different variables. They both have different scope. The scopes do not overlap. The parameter is called nStars in drawRow. It is initialised with i in main. The names do not have to be the same. ITP © Ron Poet Lecture 11

A Fixed Size Triangle This clumsy example shows repeated calls to the drawRow method. It will draw a triangle with 4 rows. public static void main(String[] arg) { Console con = new Console("Triangle"); drawRow(con, 1); drawRow(con, 2); drawRow(con, 3); drawRow(con, 4); } ITP © Ron Poet Lecture 11