CSE 142 Lecture Notes Global Constants, Parameters, Return Values

Slides:



Advertisements
Similar presentations
Building Java Programs
Advertisements

BUILDING JAVA PROGRAMS CHAPTER 3 PARAMETERS AND OBJECTS.
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.
1 Parameters. 2 Repetitive figures Consider the task of drawing the following figures: ************* ******* *********************************** **********
Copyright 2008 by Pearson Education Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs Lecture 3-1: Parameters (reading: 3.1)
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
Copyright 2008 by Pearson Education 1 Class constants and scope reading: 2.4 self-check: 28 exercises: 11 videos: Ch. 2 #5.
CS305j Introduction to ComputingNested For Loops 1 Topic 6 Nested for Loops "Complexity has and will maintain a strong fascination for many people. It.
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
Building Java Programs Chapter 3 Parameters and Objects Copyright (c) Pearson All rights reserved.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-3: Loop Figures and Constants reading: self-checks: 27 exercises:
1 BUILDING JAVA PROGRAMS CHAPTER 2 Pseudocode and Scope.
Building Java Programs Parameters and Objects. 2 Redundant recipes Recipe for baking 20 cookies: –Mix the following ingredients in a bowl: 4 cups flour.
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.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 4: Loop Figures and Constants reading:
1 BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA AND DEFINITE LOOPS.
1 CSE 142 Lecture Notes Conditional Execution with if Statements; Methods that Return Values (briefly) Chapters 3 and 4 Suggested reading: ;
Topic 6 loops, figures, constants Based on slides bu Marty Stepp and Stuart Reges from "Complexity has and will maintain.
Copyright 2008 by Pearson Education 1 Nested loops reading: 2.3 self-check: exercises: videos: Ch. 2 #4.
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.
1 Building Java Programs Chapter 2: Primitive Data and Definite Loops These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 2: Primitive Data and Definite Loops.
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.
Building Java Programs Chapter 3
Lecture 3: Method Parameters
Lecture 6: While Loops and the Math Class
Building Java Programs
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs
Math Methods that return values
Building Java Programs
Building Java Programs
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
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
Building Java Programs
Redundant recipes Recipe for baking 20 cookies:
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 3: Method Parameters
Topic 6 loops, figures, constants
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Suggested self-checks:
Building Java Programs
Drawing complex figures
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 2 Lecture 2-3: Loop Figures and Constants reading:
Presentation transcript:

CSE 142 Lecture Notes Global Constants, Parameters, Return Values Chapter 3 Suggested reading: 3.1 - 3.3, 3.4 Suggested self-checks: 1-4, 8-11 These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or modified without Marty Stepp's expressed written permission. All rights reserved.

Lecture outline using global constants passing parameters to static methods writing methods that accept parameters calling methods that return values the Math class writing methods that return values

A patterned figure Consider the task of drawing the following figure: +/\/\/\/\/\+ | | Each figure is strongly tied to the number 5 (or a multiple such as 10 ...) See code for drawing these figures.

Some repetitive code Note the repetition of numbers based on 5 in the code: public static void drawFigure1() { drawPlusLine(); drawBarLine(); } public static void drawPlusLine() { System.out.print("+"); for (int i = 1; i <= 5; i++) { System.out.print("/\\"); System.out.println("+"); public static void drawBarLine() { System.out.print("|"); for (int i = 1; i <= 10; i++) { System.out.print(" "); System.out.println("|"); It would be cumbersome to resize the figure such as by changing all the 5s into 8s. Output: +/\/\/\/\/\+ | |

A failed attempt to fix it A normal variable cannot be used to fix the problem: public static void main(String[] args) { int width = 5; drawFigure1(); } public static void drawFigure1() { drawPlusLine(); drawBarLine(); public static void drawPlusLine() { System.out.print("+"); for (int i = 1; i <= width; i++) { // ERROR System.out.print("/\\"); System.out.println("+");

Variable scope scope: The portion of a program where a given variable exists. A variable's scope is from its declaration to the end of the block (pair of { } braces) in which it was declared. If a variable is declared in a for loop (including the <initialization> or the loop's <statement(s)>, it exists until the end of that for loop. If a variable is declared in a method, it exists only in that method, until the end of the method (not in any other methods called). public static void main(String[] args) { int x = 3; for (int i = 1; i <= 10; i++) { System.out.print(x); } // i no longer exists here } // x ceases to exist here

Scope and using variables It is illegal to try to use a variable outside of its scope. public static void main(String[] args) { example(); System.out.println(x); // illegal for (int i = 1; i <= 10; i++) { int y = 5; System.out.println(y); } System.out.println(y); // illegal public static void example() { int x = 3; System.out.println(x);

Overlapping scope It is legal to declare variables with the same name, as long as their scopes do not overlap: public static void main(String[] args) { int x = 2; for (int i = 1; i <= 5; i++) { int y = 5; System.out.println(y); } for (int i = 3; i <= 5; i++) { int y = 2; int x = 4; // illegal public static void anotherMethod() { int i = 6; int y = 3; System.out.println(i + ", " + y);

Global constants global constant: A special unchangeable variable whose scope spans throughout the program. The value of a constant can only be set once, when it is being declared. It can not be changed while the program is running. Global constant syntax: public static final <type> <name> = <value> ; Constants' names are usually written in ALL_UPPER_CASE. Examples: public static final int DAYS_IN_WEEK = 7; public static final double INTEREST_RATE = .035 * 100; public static final int SSN = 658234569;

Fixing our code with constant A global constant will fix the "magic number" problem: public static final int FIGURE_WIDTH = 5; public static void main(String[] args) { drawFigure1(); } public static void drawFigure1() { drawPlusLine(); System.out.print("|"); for (int i = 1; i <= 2 * FIGURE_WIDTH; i++) { System.out.print(" "); System.out.println("|");

Another repetitive figure Now consider the task of drawing the following figures: ************* ******* ********** * * ***** * * We'd like to structure the input using static methods, but each figure is different. What can we do?

A poor solution Using what we already know, we could write a solution with the following methods: A method to draw a line of 13 stars. A method to draw a line of 7 stars. A method to draw a box of stars, size 10 x 3. A method to draw a box of stars, size 5 x 4. These methods would be largely redundant. Constants would not help us solve this problem, because we do not want to share one value but want to run similar code with many values.

A better solution A better solution would look something like this: A method to draw a line of any number of stars. A method to draw a box of stars of any size. It is possible to write parameterized methods; methods that are passed information when they are called which affects their behavior. Example: A parameterized method to draw a line of stars might ask us to specify how many stars to draw. parameter: A value given to a method by its caller, which takes the form of a variable inside the method's code. The method can use the value of this variable to adjust its behavior.

Methods with parameters Declaring a method that accepts a parameter: public static void <name> ( <type> <name> ) { <statement(s)> ; } Example: // Prints the given number of spaces. public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" ");

Passing parameters Calling a method and specifying a value for its parameter is called passing a parameter. Method call with passing parameter syntax: <name>( <value> ); Example: System.out.print("*"); printSpaces(7); System.out.print("**"); int x = 3 * 5; printSpaces(x + 2); System.out.println("***"); Output: * ** ***

How parameters are passed formal parameter: The variable declared in the method. actual parameter: The value written between the parentheses in the call. When the program executes, the actual parameter's value is stored into the formal parameter variable, then the method's code executes. printSpaces( 13 ); ... public static void printSpaces(int count) { for (int i = 1; i <= count; i++) { System.out.print(" "); } count will take the value 13 for this method call

Parameterized figure This code parameterizes the lines of stars: public static void main(String[] args) { drawLineOfStars(13); System.out.println(); drawLineOfStars(7); } public static void drawLineOfStars(int length) { for (int i = 1; i <= length; i++) { System.out.print("*"); Output: ************* *******

Some parameter details If a method accepts a parameter, it is illegal to call it without passing any value for that parameter. printSpaces(); // ILLEGAL The actual parameter value passed to a method must be of the correct type, matching the type of the formal parameter variable. printSpaces(3.7); // ILLEGAL -- must be type int Two methods may have the same name as long as they accept different parameters (this is called overloading). public static void printLineOfStars() { ... } public static void printLineOfStars(int length) { ... }

Value parameter behavior value parameter: When primitive variables (such as int or double) are passed as parameters in Java, their values are copied and stored into the method's formal parameter. Modifying the formal parameter variable's value will not affect the value of the variable which was passed as the actual parameter. int x = 23; strange(x); System.out.println(x); // this x is unaffected ... public static void strange(int x) { x = x + 1; // modifies my x System.out.println(x); } Output: 24 23

Multiple parameters A method can accept more than one parameter, separated by commas: public static void <name> ( <type> <name> , <type> <name> , ..., <type> <name> ) { <statement(s)> ; } Example: public static void printPluses(int lines, int count) { for (int line = 1; line <= lines; line++) { for (int i = 1; i <= count; i++) { System.out.print(" "); System.out.println();

Parameterized box figure This code parameterizes the boxes of stars: public static void main(String[] args) { drawBoxOfStars(10, 3); System.out.println(); drawBoxOfStars(4, 5); } public static void drawBoxOfStars(int width, int height) { drawLineOfStars(width); for (int line = 1; line <= height - 2; line++) { System.out.print("*"); printSpaces(width - 2); System.out.println("*");

Java's Math class Java has a class called Math that has several useful methods that perform mathematical calculations. The Math methods are called by writing: Math. <name> ( <values> ); Method name Description abs(value) absolute value cos(value) cosine, in radians log(value) logarithm base e max(value1, value2) larger of two values min(value1, value2) smaller of two values pow(value1, value2) value1 to the value2 power random() random double between 0 and 1 sin(value) sine, in radians sqrt(value) square root

Methods that "return" values The methods of the Math class do not print their results to the console. Instead, a call to one of these methods can be used as an expression or part of an expression. The method evaluates to produce (or return) a numeric result. The result can be printed or used in a larger expression. Example: int squareRoot = Math.sqrt(121); System.out.println(squareRoot); // 11 int absoluteValue = Math.abs(-50); System.out.println(absoluteValue); // 50 System.out.println(Math.min(3, 7) + 2); // 5

Methods that return values Declaring a method that returns a value: public static <type> <name> ( <type> <name> ) { <statement(s)> ; } Returning a value from a method: return <value> ; Example: // Returns the given number cubed (to the third power). public static int cube(int number) { return number * number * number;

Example returning methods // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { return 5.0 / 9.0 * degreesF - 32; } // Converts Celsius to Fahrenheit. public static double cToF(double degreesC) { return 9.0 / 5.0 * degreesC + 32; // Converts kilograms to pounds. public static double weightLb(double weightKG) { return 2.2 * weightKG;