Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,

Slides:



Advertisements
Similar presentations
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Advertisements

Datalogi A 1: 8/9. Book: Cay Horstmann: Big Java or Java Consepts.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Begin Java having used Alice Pepper - Some slides from Alice in Action with Java.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
1 Interactive Applications (CLI) Interactive Applications Command Line Interfaces Project 1: Calculating BMI Example: Factoring the Solution Reading for.
Unit 2: Java Introduction to Programming 2.1 Initial Example.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Methods Material from Chapters 5 & 6. Terminology  Method, function, procedure, subroutine  all mean approximately the same thing »functions may return.
Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Introduction to Python
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Java Thanks to Dan Lunney (SHS). Java Basics File names The “main” method Output to screen Escape Sequence – Special Characters format()
11 Chapter 5 METHODS CONT’D. 22 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Objects are passed by reference.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create.
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2.
Introduction Chapter 1 8/31 & 9/1 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase()
By Mr. Muhammad Pervez Akhtar
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
Review of CSCI 1226 What You Should Already Know.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Data, Classes, and Objects Classes with Data Classes for Data (Chapter 5)
Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2.
CompSci 230 S Programming Techniques
Chapter 2 Basic Computation
Input/Output.
Chapter 2 More on Math More on Input
Building Java Programs
The Program Class, the main Method, Variables, Output, and Input
Introduction to Computer Science / Procedural – 67130
Data, Classes, and Objects
Variables, Expressions, and IO
User input We’ve seen how to use the standard output buffer
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Program Style Console Input and Output
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
IDENTIFIERS CSC 111.
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Building Java Programs
MSIS 655 Advanced Business Applications Programming
IFS410 Advanced Analysis and Design
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
Building Java Programs
Anatomy of a Java Program
Presentation transcript:

Methods II Material from Chapters 5 & 6

Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods, but no main  In order to use them, we need a program…  program tells non-program what to do  …so we need two (or more) files  code for program file will be in yellow  code for non-program file(s) will be in green

Last Time  Methods that return values  method call: returnType var = Class.name(arg);  method definition: public class Class { public static returnType name(pType param) { // body goes here (if needed) // body goes here (if needed) return result; return result; }} »need to fill in return type, parameters, body & result »there may be more parameters, or none

This Time  Methods that do not return a value  “procedures”  AKA: “void methods”, “void functions” »I don’t like “void functions”, but some people do  Used differently than function methods  void method call: Class.name(arg);  there’s no return value, and so nothing to “use” »may be no arguments, or several

Two Kinds of Methods  Some methods return a value to you  nextInt returns an int  fahrenheitFromCelsius returns a double  equalsIgnoreCase returns a boolean  These called value-returning methods  Other methods do not return values  print and println, for example  Those are called void methods

Value-Returning Function Calls word = keyboard.next(); while (!word.equals(“.”))  Value-returning functions used in expressions  often in assignment statements  also in logical expressions Method ArgumentsMethod Name Object

Void Function Calls System.out.print(“Enter a #”); System.out.print(“\n\n”);  Void functions used as complete statements  not in any expression  have no value (“void” = empty/nothing) Method ArgumentsMethod Name Object

Return or No Return?  Void methods do things; don’t return things  println prints a String  the String gets printed  the String does not get returned String s = System.out.println(“Hello?”);  nothing gets returned! int n = System.out.println(“10”); incompatible types: void cannot be converted to String incompatible types: void cannot be converted to int

Exercise  Void or value-returning?  & what kind of value does each VRM return? if (answer.startsWith(“Y”)) { double x = Math.pow(3, 6); double x = Math.pow(3, 6); int n = kbd.nextInt(); int n = kbd.nextInt(); System.out.println(“Hello!”); System.out.println(“Hello!”); myWin.setVisible(true); myWin.setVisible(true); double cm = Converter.cmFromFeetInches(n, x); double cm = Converter.cmFromFeetInches(n, x); thingamajig.doStuff(cm, x, that.get(n)); thingamajig.doStuff(cm, x, that.get(n));} Note: there are two method calls on the last line. How can we find out what kind of value get returns?

void Method Definition  Very similar to function method definition  put “void” for the return type »“void” means “nothing”: the method returns nothing  don’t use a return command »there’s nothing to return! public class Class { public static void name(pType param) { // body goes here // body goes here }}

What’s it for?  It’s to do things  for example, to print something: System.out.println(“Hello, World!”);  System.out is the object (it’s a PrintWriter) »System is a class, and out belongs to System  println is the name of the method  println expects to be given a String »(or some other thing, or nothing; it’s complicated)

Example  Write a method that prints out the self- identification for A07:  Including the blank lines before and after  Call like this: Utilities.printA07Identification(); A Young, Mark CSCI Fall 2015 A07 -- due What is the method’s name? What class is it defined in? How can we tell it’s a void method?

Naming Methods  Method names in mixed case  capital letter for 2 nd and subsequent words  Value-returning methods have noun-like names  say what the value is: fahrenheitFromCelsius  void functions have command-like names  tell program what to do: printA07Identification

Exercise  Create names for the following methods  gives us the factorial value of a number »(e.g. 5! = 5 * 4 * 3 * 2 * 1 = 120)  figures out how many students failed a test a)... and returns that value to us b)... and prints a message telling us the number  draws a snowman in a (given) window

printA07Identification  Start with just a stub  a small definition that compiles public class Utilities { public static void printA07Identification() { public static void printA07Identification() { }}  Note: void methods have no return command »so void method stub can actually be empty  maybe S.o.pln(“Print A07 identification here”);

printA07Identification  Add code to do what needs doing  one command, or many public static void printA07Identification() { System.out.println(); System.out.println(); System.out.println(“A Young, Mark”); System.out.println(“A Young, Mark”); System.out.println(“CSCI Fall 2015”); System.out.println(“CSCI Fall 2015”); System.out.println(“A07 -- due ”); System.out.println(“A07 -- due ”); System.out.println(); System.out.println();}

Commenting Methods  Methods should have javadoc comments  start with /**, end with */  at least a brief description of the method: /** Prints the identification information for A07. */ /** Converts distance in feet and inches to cm. */  hover over method header in Navigator pane… »lower left side of NetBeans window  …to see your comment

Commenting Methods  Better (but NOT REQUIRED):  for each parameter (if any)  if it’s a value-returning method /** * Converts distance from feet and inches to centimetres. * Converts distance from feet and inches to centimetres. * ft (whole) number of feet in the distance ft (whole) number of feet in the distance in number of (extra) inches in the distance in number of (extra) inches in the distance same distance, but measured in centimetres same distance, but measured in centimetres */ */

Commenting Methods  A longer description may be appropriate.  add HTML markup to format the comment /** * Prints the identification information for A07. * Prints the identification information for A07. * * * The identification consists of the author’s A-number and name, * The identification consists of the author’s A-number and name, * the course title and term, and the assignment number and due date. * the course title and term, and the assignment number and due date. * These are printed on three lines, with double hyphens between the * These are printed on three lines, with double hyphens between the * two items on each line. * two items on each line. */ */ is HTML for “start a new paragraph.” You DO NOT need to learn HTML for this course!

Arguments to a Method  Some methods need more information  what is it you want me to print?  what distance do you want me to convert?  In parentheses after the method name System.out.println(“OK!”); cm = Converter.cmFromFeetInches(3, 5);  Still need parentheses even if no arguments num = kbd.nextInt(); Utilities.printA07Identification();

Arguments and Parameters  Method definition needs one parameter for each argument  parameter is a variable to hold the argument  Parameter must be the right data type  argument is double  parameter is double  argument is String  parameter is String  argument is boolean  parameter is boolean  argument is int  parameter is int (or double) »computer will change int to double when it needs to

Method Parameters public static double fahrenheitFromCelsius(double degC) { …}  double degC  needs to be given a double value (int is OK) »it will be given a value! »not giving it a value is a mistake (syntax error)  it will call the value it’s been given degC »it might be 10.0, 37.5, -40.0, , … »whatever it is, it’s saved in degC

Method Parameters public static double cmFromFeetInches(int ft, double in) { …}  This method has two parameters  it’s expecting to be given two things  the first thing will be an int (we’ll call it ft)  the second thing will be a double (in) Arguments & parameters match up in order – first argument  first parameter, second argument  second parameter, …

Parameters are Local  The method’s parameter(s) can only be used in that method  just like a for loop’s loop control variable  You can give it any (valid) name you want  doesn’t matter who else uses that name »or if no one else uses that name  should say what it holds, tho »ft holds # of feet, degC holds a temp. in Celsius.

Local Variables for (int c = 0; c < 10; ++c) { Converter.fahrenheitFromCelsius(c); Converter.fahrenheitFromCelsius(c); Sopln(degC + “C is ” + degF + “F”); Sopln(degC + “C is ” + degF + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = * degC / 5.0; double degF = * degC / 5.0; return degF; return degF;} Symbol not found: degC Symbol not found: degF Assign return value to new variable

Hacking for (int c = 0; c < 10; ++c) { double degC, degF; double degC, degF; Converter.fahrenheitFromCelsius(c); Converter.fahrenheitFromCelsius(c); Sopln(degC + “C is ” + degF + “F”); Sopln(degC + “C is ” + degF + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = * degC / 5.0; double degF = * degC / 5.0; return degF; return degF;} degC not initialized degF not initialized Assign return value to new variable

Hacking for (int c = 0; c < 10; ++c) { double degC = 0.0, degF = 0.0; double degC = 0.0, degF = 0.0; Converter.fahrenheitFromCelsius(c); Converter.fahrenheitFromCelsius(c); Sopln(degC + “C is ” + degF + “F”); Sopln(degC + “C is ” + degF + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = * degC / 5.0; double degF = * degC / 5.0; return degF; return degF;} Assign return value to new variable 0.0C is 0.0F

Hacking for (int c = 0; c < 10; ++c) { double degC = 0.0, degF = 0.0; double degC = 0.0, degF = 0.0; degF = Converter.fahrenheitFromCelsius(c); degF = Converter.fahrenheitFromCelsius(c); Sopln(degC + “C is ” + degF + “F”); Sopln(degC + “C is ” + degF + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = * degC / 5.0; double degF = * degC / 5.0; return degF; return degF;} 0.0C is 32.0F 0.0C is 33.8F 0.0C is 35.6F 0.0C is 37.4F 0.0C is 39.2F

Local Variables for (int c = 0; c < 10; ++c) { double f = Converter.fahrenheitFromCelsius(c); double f = Converter.fahrenheitFromCelsius(c); Sopln(c + “C is ” + f + “F”); Sopln(c + “C is ” + f + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = * degC / 5.0; double degF = * degC / 5.0; return degF; return degF;} 0C is 32.0F 1C is 33.8F 2C is 35.6F 3C is 37.4F 4C is 39.2F

Arguments  Remember that arguments are extra information we give to a method  information it needs to do its job  Each time you call the method, the arguments are “passed to” the method, and it uses them  System.out.println(“Hello!”); prints “Hello!”  System.out.println(“Bye!”); prints “Bye!

Arguments to User Methods  User methods are the same! Utilities.printAssignmentInformation(7, “ ”); Utilities.printAssignmentInformation(8, “ ”); A Young, Mark CSCI Fall 2014 A07 -- due A Young, Mark CSCI Fall 2014 A08 -- due

Exercise  Write that method: Utilities.printAssignmentInformation(7, “Friday”);  What’s its name?  What class is it in?  What kinds of arguments does it take? »what are those arguments for? A Young, Mark CSCI Fall 2015 A07 -- due Friday System.out.printf(“A%02d”, 1); will print A01

More Utilities Methods  A class with helpful printing methods  use it like this: Utilities.printTitle(“Utilities Demo”); Utilities.printParagraph(“This program demonstrates ” + “the Utilities class.”); Utilities.printParagraph(“This paragraph was produced ” + “by the printParagraph method.”); Utilities.printParagraph(“This paragraph’s much longer ” + “than the one above, and needs to be \“wrapped\” ” + “on the output line. The method does that for us!”);

Titles and Paragraphs  printTitle  print underlined, with blank lines  printParagraph  wrap words, add blank line Utilities Demo This program demonstrates the Utilities class. This paragraph was produced by the printParagraph method. This paragraph’s much longer than the one above and needs to be “wrapped” on the output line. The method does that for us!

Utilities Class Stubs public class Utilities{ public static void printAssignmentIdentification (int a, String d) { public static void printAssignmentIdentification (int a, String d) { } public static void printTitle(String title) { } public static void printParagraph(String text) { }}

printTitle Body public void printTitle(String title) { System.out.print("\n" + title + "\n"); System.out.print("\n" + title + "\n"); for (int i = 1; i <= title.length(); i++) for (int i = 1; i <= title.length(); i++) System.out.print('-'); System.out.print('-'); System.out.print("\n\n"); System.out.print("\n\n");}  print blank line and title; end title line  for each letter in the title »print a hyphen (to underline that letter)  end underline line, print blank line

printParagraph Body  printParagraph is more complicated  needs to break the String into words  needs to print each word, BUT…  … before it prints a word, it needs to know if there’s enuf space for it »if not, we need to end the line before we print it »so needs to keep track of how much space is used  but it’s just a programming problem »same as if we’d asked for a program to do it

Fitting Words on Lines  Check for space first; maybe go to new line  Print word after that printParagraph(“These are the words to print on the screen, ” + “which is only 20 spaces wide.”); Thesearethewordsto printonthescreen,to screen,whichisonly 20spaceswide.

Fitting Words on a Line  Track how many spaces used so far int spacesUsedSoFar = 0;  Check word’s length (plus one for the space after!) int spacesNeeded = word.length() + 1;  If there’s not enuf space, go to the next line if (spacesUsedSoFar + spacesNeeded > MAX_LINE_LENGTH) { System.out.println(); spacesUsedSoFar = 0; System.out.println(); spacesUsedSoFar = 0;}  Print the word; update the number of spaces used System.out.print(word);spacesUsedSoFar += spacesNeeded;

Breaking a String into Words  We know how to get words from the user Scanner kbd = new Scanner(System.in); String userWord = kbd.next();  System.in is (essentially) the keyboard  kbd reads from the keyboard (hence its name)  Only need to change System.in to the String Scanner str = new Scanner(“One two three”); String stringWord = str.next();// stringWord == “One”  str reads from the String!

The Scanner in printParagraph  The String to print is given to the method  the method creates the Scanner on the String public static void printParagraph(String text) { Scanner para = new Scanner(text); Scanner para = new Scanner(text); while (para.hasNext()) { while (para.hasNext()) { String word = para.next(); String word = para.next();  the hasNext() method checks whether there are any more words in the String ».: the loop runs until there are no more words left

Objects  A Scanner is an object  it has its own data as well as its own methods  kbd knows it must read from the keyboard  str knows it must read from a String  How? We told it when we made it! kbd = new Scanner(System.in); str = new Scanner(text);  each object remembers its own data  that’s useful!

Next Time  How do we write classes for objects?