Building Java Programs

Similar documents
Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

AP Computer Science A. Return values

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

CSc 110, Spring Lecture 11: return values and math

CSc 110, Autumn Lecture 10: return values and math

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

Lecture 6: While Loops and the Math Class

CS 112 Introduction to Programming

CS 112 Introduction to Programming

CSc 110, Spring Lecture 7: Graphics, return values and math

Redundant recipes. Building Java Programs Chapter 3. Parameterized recipe. Redundant figures

Building Java Programs Chapter 3

Topic 12 more if/else, cumulative algorithms, printf

Building Java Programs

AP Computer Science. if/else, return values. Copyright 2010 by Pearson Education

AP CS Java Syntax Summary: (version 3)

Parameters. Repetitive figures. A solution? Parameterization. Declaring parameterized methods. Generalizing methods. Readings: 3.1

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Returns & if/else. Parameters and Objects

CIS133J. Working with Numbers in Java

CSE 373. Data Types and Manipulation; Arrays. slides created by Marty Stepp

CS110: PROGRAMMING LANGUAGE I

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

The Math Class. Using various math class methods. Formatting the values.

AP CS Java Syntax Summary: (version 4)

JAVASCRIPT BASICS. JavaScript Math Functions. The Math functions helps you to perform mathematical tasks

Introduction to Computer Science Unit 2. Notes

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

A Balanced Introduction to Computer Science, 3/E

CSc 110, Spring Lecture 11: if / else. Adapted from slides by Marty Stepp and Stuart Reges

Introduction to Computer Science and Object-Oriented Programming

Introduction to Computer Science Unit 2. Notes

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Solving Equations with Inverse Operations

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Variables, Types, Operations on Numbers

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Calculations, Formatting and Conversions

Computer Programming I - Unit 2 Lecture 1 of 13

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods / Functions

CISC 110 Week 3. Expressions, Statements, Programming Style, and Test Review

REVIEW. while (condition) { <body> for (<init> ; <condition> ; <increment>) { } if (condition) { <command> } else { <command> }

Chapter 6 Methods. Dr. Hikmat Jaber

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

4. Java Project Design, Input Methods

AP CS Java Syntax Summary: (version 5)

Functions, Randomness and Libraries

Object Oriented Methods : Deeper Look Lecture Three

Study Guide and Review - Chapter 10

Study Guide and Review - Chapter 10

Downloaded from Chapter 2. Functions

Variable Manipulator Driver. Installation and Usage Guide. Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow

Chapter 4 Mathematical Functions, Characters, and Strings

Methods CSC 121 Fall 2014 Howard Rosenthal

Introduction to FORTRAN

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

AP CS Unit 3: Control Structures Notes

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Coding in JavaScript functions

Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

Lecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved.

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

CT 229 Java Syntax Continued

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Module 1: Types and Expressions

What did we talk about last time? Examples switch statements

II. Functions. 61. Find a way to graph the line from the problem 59 on your calculator. Sketch the calculator graph here, including the window values:

Methods: A Deeper Look

CS 302: Introduction to Programming

The equation of the axis of symmetry is. Therefore, the x-coordinate of the vertex is 2.

Mat 2170 Week 6. Methods. Week 6. Mat 2170 Week 6. Jargon. Info Hiding. Math Lib. Lab 6. Exercises. Methods. Spring 2014

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

M e t h o d s a n d P a r a m e t e r s

Advanced Object Concepts

Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017

Projectile Motion. A.1. Finding the flight time from the vertical motion. The five variables for the vertical motion are:

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Methods CSC 121 Fall 2016 Howard Rosenthal

VBScript: Math Functions

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

COMP Primitive and Class Types. Yi Hong May 14, 2015

Binghamton University. CS-211 Fall Data Conversion. software diversity in action

Lecture 2: Python Arithmetic

Module 4: Characters, Strings, and Mathematical Functions

EXERCISE SET 10.2 MATD 0390 DUE DATE: INSTRUCTOR

Transcription:

Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2, 2.1-2.2 Method name Math.abs(value) Math.ceil(value) Math.floor(value) Java's Math class Description absolute value rounds up rounds down Math.log10(value) logarithm, base 10 Math.max(value1, value2) Math.min(value1, value2) Math.pow(base, exp) larger of two values smaller of two values base to the exp power Math.random() random double between 0 and 1 Math.round(value) Math.sqrt(value) Math.sin(value) Math.cos(value) Math.tan(value) Math.toDegrees(value) Math.toRadians(value) nearest whole number square root sine/cosine/tangent of an angle in radians convert degrees to radians and back Constant Description Math.E 2.7182818... Math.PI 3.1415926... 2 1

No output? Simply calling these methods produces no visible result. public class TestMath { Math.pow(3, 4); // no output! 3 No output! Math method calls use a feature called return values that cause them to be treated as expressions. The program runs the method, computes the answer, and then "replaces" the call with its computed result value. Math.pow(3, 4); // no output 81.0; // no output To see the result, we must print it or store it in a variable. double result = Math.pow(3, 4); System.out.println(result); // 81.0 4 2

Return return: To send out a value as the result of a method. The opposite of a parameter Parameters send information in from the caller to the method. Return values send information out from a method to its caller. A call to the method can be used as part of an expression. -42 Math.abs(-42) main 42 2.71 3 Math.round(2.71) 5 Why return and not print? It might seem more useful for the Math methods to print their results rather than returning them. Why don't they? Answer: Returning is more flexible than printing. We can compute several things before printing: double pow1 = Math.pow(3, 4); double pow2 = Math.pow(10, 6); System.out.println("Powers are " + pow1 + " and " + pow2); We can combine the results of many computations: double k = 13 * Math.pow(3, 4) + 5 - Math.sqrt(17.8); 6 3

Math questions Evaluate the following expressions: Math.abs(-1.23) Math.pow(3, 2) Math.pow(10, -2) Math.sqrt(121.0) - Math.sqrt(256.0) Math.round(Math.PI) + Math.round(Math.E) Math.ceil(6.022) + Math.floor(15.9994) Math.abs(Math.min(-3, -5)) Math.max and Math.min can be used to bound numbers. Consider an int variable named age. What statement would replace negative ages with 0? What statement would cap the maximum age to 40? 7 Incompatible types Some Math methods return double or other non-int types. int x = Math.pow(10, 3); // ERROR: incompatible types What if you wanted to store a double in an int variable? (maybe you don t care about the decimal part) 8 4

Type casting type cast: A conversion from one type to another. To promote an int into a double to get exact division from / To truncate a double from a real number to an integer Syntax: (<type>)<expression> Examples: double result = (double) 19 / 5; // 3.8 int result2 = (int)result; // 3 int x = (int)math.pow(10, 3); // 1000 9 More about type casting Type casting has high precedence and only casts the item immediately next to it. double x = (double) 1 + 1 / 2; // 1.0 double y = 1 + (double) 1 / 2; // 1.5 You can use parentheses to force evaluation order. double average = (double)(a + b + c) / 3; A conversion to double can be achieved in other ways. double average = 1.0 * (a + b + c) / 3; 10 5

Returning a value public static <type> <name>(<parameters>) { <statement(s)>;... return <expression>; Example: // Returns the slope of the line between the given points. public static double slope(int x1, int y1, int x2, int y2) { double dy = y2 - y1; double dx = x2 - x1; return dy / dx; slope(5, 11, 1, 3) returns 2.0 11 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: public static double ftoc(double degreesf) { return 5.0 / 9.0 * (degreesf - 32); 12 6

Common error: Not storing Many students incorrectly think that a return statement sends a variable's name back to the calling method. slope(0, 0, 6, 3); System.out.println("The slope is " + result); // ERROR: result not defined public static double slope(int x1, int y1, int x2, int y2) { double dy = y2 - y1; double dx = x2 - x1; double result = dy / dx; return result; 13 Fixing the common error Instead, returning sends the variable's value back. The returned value must be stored into a variable or used in an expression to be useful to the caller. double s = slope(0, 0, 6, 3); System.out.println("The slope is " + s); public static double slope(int x1, int y1, int x2, int y2) { double dy = y2 - y1; double dx = x2 - x1; double result = dy / dx; return result; 14 7

Common error variation Particularly confusing is conflating the return variable with a variable in the calling method. Your program will compile, but you won t get the right result! public class ReturnExample { int x = 1; addone(x); System.out.println("x = " + x); public static int addone(int x) { x = x + 1; return x; 15 Don t ignore the return value! Just because the return variable in the called method has the same name as the variable in the calling method, they are NOT the same. Think scope! public class ReturnExample { int x = 1; addone(x); System.out.println("x = " + x); public class ReturnExample { int x = 1; x = addone(x); System.out.println("x = " + x); public static int addone(int x) { x = x + 1; return x; public static int addone(int x) { x = x + 1; return x; 16 8

Exercise In physics, the displacement of a moving body represents its change in position over time while accelerating. Given initial velocity v 0 in m/s, acceleration a in m/s 2, and elapsed time t in s, the displacement of the body is: Displacement = v 0 t + ½ a t 2 Write a method displacement that accepts v 0, t, and a and computes and returns the change in position. Example: displacement(3.0, 4.0, 5.0) returns 52.0 17 Exercise solution public static double displacement(double v0, double t, double a) { double d = v0 * t + 0.5 * a * Math.pow(t, 2); return d; 18 9

Exercise If you drop two balls, which will hit the ground first? Ball 1: height of 600m, initial velocity = 25 m/sec downward Ball 2: height of 500m, initial velocity = 15 m/sec downward Write a program that determines how long each ball takes to hit the ground (and draws each ball falling). Total time is based on the force of gravity on each ball. Acceleration due to gravity 9.81 m/s 2, downward Displacement = v 0 t + ½ a t 2 19 Ball solution // Simulates the dropping of two balls from various heights. import java.awt.*; public class Balls { public final static int PANEL_HEIGHT = 600; DrawingPanel panel = new DrawingPanel(600, 600); Graphics g = panel.getgraphics(); int ball1x = 100, initialball1y = 600, v01 = 25; int ball2x = 200, initialball2y = 500, v02 = 15; // draw the balls at each time increment for (double t = 0; t <= 10.0; t = t + 0.1) { double height1 = initialball1y - displacement(v01, t, 9.81); g.filloval(ball1x, PANEL_HEIGHT - (int)height1, 10, 10); double height2 = initialball2y - displacement(v02, t, 9.81); g.filloval(ball2x, PANEL_HEIGHT - (int)height2, 10, 10); panel.sleep(50); panel.clear(); // pause for 50 ms... 20 10