Building Java Programs

Slides:



Advertisements
Similar presentations
BUILDING JAVA PROGRAMS CHAPTER 3 PARAMETERS AND OBJECTS.
Advertisements

Nested for loops Cont’d. 2 Drawing complex figures Use nested for loops to produce the following output. Why draw ASCII art? –Real graphics require a.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
1 BUILDING JAVA PROGRAMS CHAPTER 4 CONDITIONAL EXECUTION.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs Lecture 3-1: Parameters (reading: 3.1)
Copyright 2008 by Pearson Education 1 Class constants and scope reading: 2.4 self-check: 28 exercises: 11 videos: Ch. 2 #5.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs.
Topic 7 parameters Based on slides bu Marty Stepp and Stuart Reges from "We're flooding people with information. We.
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Conditionals (Cont’d). 2 Nested if/else question Formula for body mass index (BMI): Write a program that produces output like the following: This program.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 7: Return values, Math, and double reading: 3.2,
Building Java Programs Chapter 3 Parameters and Objects Copyright (c) Pearson All rights reserved.
Building Java Programs Parameters and Objects. 2 Redundant recipes Recipe for baking 20 cookies: –Mix the following ingredients in a bowl: 4 cups flour.
Copyright 2010 by Pearson Education Building Java Programs Chapter 1 Lecture 1-2: Static Methods reading:
Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
1 BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA AND DEFINITE LOOPS.
Copyright 2010 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
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.
Copyright 2011 by Pearson Education Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2,
Copyright 2009 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1 self-check: #1-6 exercises: #1-3 videos: Ch.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Copyright 2010 by Pearson Education The if/else statement reading: 4.1, 4.6.
Building Java Programs Chapter 3
Lecture 3: Method Parameters
Building Java Programs
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs
Building Java Programs
Math Methods that return values
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs Chapter 4
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs Chapter 4
CSc 110, Spring 2017 Lecture 5: Constants and Parameters
Topic 7 parameters "We're flooding people with information. We need to feed it through a processor. A human must turn information into intelligence or.
Building Java Programs
Redundant recipes Recipe for baking 20 cookies:
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Static Methods
Lecture 7: Methods AP Computer Science Principles
Lecture 3: Method Parameters
Factoring if/else code
Building Java Programs
Building Java Programs
Building Java Programs
CSE 142 Lecture Notes Global Constants, Parameters, Return Values
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 1 Lecture 1-2: Static Methods reading:
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 – 3.4, 4.1, 4.5
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

Building Java Programs static methods, constants reading: 1.4 - 1.5, 2.4 – 2.5, 3.1 - 3.2

Gives your method a name so it can be executed 2/24/2019 Declaring a method Gives your method a name so it can be executed Syntax: public static void name() { statement; statement; ... statement; } Example: public static void printWarning() { System.out.println("This product causes cancer"); System.out.println("in lab rats and humans."); }

Executes the method's code 2/24/2019 Calling a method Executes the method's code Syntax: name(); You can call the same method many times if you like. Example: printWarning(); Output: This product causes cancer in lab rats and humans.

Program with static method public class FreshPrince { public static void main(String[] args) { rap(); // Calling (running) the rap method System.out.println(); rap(); // Calling the rap method again } // This method prints the lyrics to my favorite song. public static void rap() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); Output: Now this is the story all about how My life got flipped turned upside-down

When to use methods Place statements into a static method if: The statements are related structurally, and/or The statements are repeated. You should not create static methods for: An individual println statement. Only blank lines. (Put blank printlns in main.) Unrelated or weakly related statements. (Consider splitting them into two smaller methods.)

Redundant figures Consider the task of printing the following lines/boxes: ************* ******* *********************************** ********** * * ***** * *

A redundant solution This code is redundant. Would variables help? public class Stars1 { public static void main(String[] args) { lineOf13(); lineOf7(); lineOf35(); box10x3(); box5x4(); } public static void lineOf13() { for (int i = 1; i <= 13; i++) { System.out.print("*"); System.out.println(); public static void lineOf7() { for (int i = 1; i <= 7; i++) { public static void lineOf35() { for (int i = 1; i <= 35; i++) { ... This code is redundant. Would variables help? What is a better solution? line - A method to draw a line of any number of stars. box - A method to draw a box of any size.

Parameterization parameter: A value passed to a method by its caller. Instead of lineOf7, lineOf13, write line to draw any length. When declaring the method, we will state that it requires a parameter for the number of stars. When calling the method, we will specify how many stars to draw. main line ******* 7 ************* 13

Declaring parameters A method can accept multiple parameters. (separate by , ) When calling it, you must pass values for each parameter. Java: public static void <name>(<type> <name>, ..., <type> <name>) { <statement>(s); } Python: def <name>(<name>, ..., <name>) { <statement>(s)

Passing parameters Calling a method and specifying values for its parameters Java: <name>(<expression>, … , <expression>); Python: <name>(<expression>, … , <expression>) The same in both languages!

Parameters example public static void main(String[] args) { printNumber(4, 9); printNumber(17, 6); printNumber(8, 0); printNumber(0, 8); } public static void printNumber(int number, int count) { for (int i = 1; i <= count; i++) { System.out.print(number); System.out.println(); Output: 444444444 171717171717 00000000

Stars solution // Prints several lines and boxes made of stars. // Third version with multiple parameterized methods. public class Stars3 { public static void main(String[] args) { line(13); line(7); line(35); System.out.println(); box(10, 3); box(5, 4); box(20, 7); } // Prints the given number of stars plus a line break. public static void line(int count) { for (int i = 1; i <= count; i++) { System.out.print("*"); ...

Stars solution, cont'd. ... // Prints a box of stars of the given size. public static void box(int width, int height) { line(width); for (int line = 1; line <= height - 2; line++) { System.out.print("*"); for (int space = 1; space <= width - 2; space++) { System.out.print(" "); } System.out.println("*");

Returning a value When Java reaches a return statement: public static type name(parameters) { statements; ... return expression; } When Java reaches a return statement: it evaluates the expression it substitutes the return value in place of the call it goes back to the caller and continues after the method call

Return examples // Converts degrees Fahrenheit to Celsius. public static double fToC(double degreesF) { double degreesC = 5.0 / 9.0 * (degreesF - 32); return degreesC; } // Computes triangle hypotenuse length given its side lengths. public static double hypotenuse(int a, int b) { double c = Math.sqrt(a * a + b * b); return c; You can shorten the examples by returning an expression: return 5.0 / 9.0 * (degreesF - 32);

Common error: Not storing Many students incorrectly think that a return statement sends a variable's name back to the calling method. public static void main(String[] args) { slope(0, 1, 6, 3); System.out.println("The slope is " + result); // ERROR: } // cannot find symbol: result public static double slope(int x1, int x2, int y1, int y2) { double dy = y2 - y1; double dx = x2 - x1; double result = dy / dx; return result; }

Fixing the common error Returning sends the variable's value back. Store the returned value into a variable or use it in an expression. public static void main(String[] args) { double s = slope(0, 0, 6, 3); System.out.println("The slope is " + s); } public static double slope(int x1, int x2, int y1, int y2) { double dy = y2 - y1; double dx = x2 - x1; double result = dy / dx; return result;

Exercise Alter the BMI program from last time to add methods. Methods should contain: The statements are related structurally, and/or The statements are repeated. Enter next person's information: height (in inches)? 70.0 weight (in pounds)? 194.25 BMI = 27.868928571428572 overweight Is there more information to enter? 42

Exercise solution // This program computes people's body mass index (BMI) and // compares them. The code uses Scanner for input, and parameters/returns. import java.util.*; // so that I can use Scanner public class Week3 { public static void main(String[] args) { intro(); Scanner console = new Scanner(System.in); int countNormal = 0; int total = 0; int again = 42; while (again != 0) { total++; System.out.println("Enter next person's information:"); System.out.print("height (in inches)? "); double height = console.nextDouble(); System.out.print("weight (in pounds)? "); double weight = console.nextDouble(); double bmi = calcBMI (weight, height); System.out.println("BMI = " + bmi); countNormal += printType(bmi); System.out.print("Is there more information to enter? "); again = console.nextInt(); } stats(countNormal, total); } …

Exercise solution Contd. public static void intro() { System.out.println("This program reads height and weight data and"); System.out.println("Computes body mass index (BMI)."); } public static double calcBMI (double weight, double height) { double bmi = weight / (height * height) * 703; return bmi; } public static void stats(int countNormal, int total) { System.out.println("Total count of people = " + + total); System.out.println("Percentage of people normal weight = " + 1.0 * countNormal / total); } public static int printType(double bmi) { if (bmi < 18.5) { System.out.println("underweight"); } else if (bmi < 25) { System.out.println("normal"); return 1; } else if (bmi < 30) { System.out.println("overweight"); } else { System.out.println("obese"); } return 0; } }

Class constants class constant: A fixed value visible to the whole program. value can be set only at declaration; cannot be reassigned Syntax: public static final type name = value; name is usually in ALL_UPPER_CASE Examples: public static final int DAYS_IN_WEEK = 7; public static final double INTEREST_RATE = 3.5; public static final int SSN = 658234569;

2/24/2019 Using a constant public class Sign { public static final int HEIGHT = 5; public static void main(String[] args) { drawLine(); drawBody(); } public static void drawLine() { System.out.print("+"); for (int i = 1; i <= HEIGHT * 2; i++) { System.out.print("/\\"); System.out.println("+"); public static void drawBody() { for (int line = 1; line <= HEIGHT; line++) { System.out.print("|"); for (int spaces = 1; spaces <= HEIGHT * 4; spaces++) { System.out.print(" "); System.out.println("|"); 23