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

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

Lecture 6: While Loops and the Math Class

CSc 110, Spring Lecture 11: return values and math

CSc 110, Autumn Lecture 10: return values and math

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Topic 12 more if/else, cumulative algorithms, printf

Building Java Programs Chapter 3

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

Building Java Programs

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

Returns & if/else. Parameters and Objects

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

AP CS Java Syntax Summary: (version 3)

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

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

Introduction to Computer Science Unit 2. Notes

CIS133J. Working with Numbers in Java

Introduction to Computer Science Unit 2. Notes

CS110: PROGRAMMING LANGUAGE I

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

AP CS Java Syntax Summary: (version 4)

Topic 12 more if/else, cumulative algorithms, printf

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

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

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

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

AP CS Unit 3: Control Structures Notes

Methods CSC 121 Fall 2014 Howard Rosenthal

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

Computer Programming I - Unit 2 Lecture 1 of 13

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

Introduction to Computer Science and Object-Oriented Programming

Chapter 4 Mathematical Functions, Characters, and Strings

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

Calculations, Formatting and Conversions

Chapter 5 Methods / Functions

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

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

Problem 7.4: Racetrack

Variables, Types, Operations on Numbers

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

CT 229 Java Syntax Continued

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Chapter 6 Methods. Dr. Hikmat Jaber

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

Lecture 2: Operations and Data Types

Midterm Examination (MTA)

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Topic 5 for loops and nested loops

AP CS Java Syntax Summary: (version 5)

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Building Java Programs

Topic 27 classes and objects, state and behavior

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Building Java Programs

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

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

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

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

Sta$cs and forma.ng numbers

Since a projectile moves in 2-dimensions, it therefore has 2 components just like a resultant vector: Horizontal Vertical

Topic 9 More Graphics. Based on slides bu Marty Stepp and Stuart Reges from

First of all, we need to know what it means for a parameterize curve to be differentiable. FACT:

Important Java terminology

Building Java Programs

4. Java Project Design, Input Methods

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

Downloaded from Chapter 2. Functions

What did we talk about last time? Examples switch statements

COSC 243. Data Representation 3. Lecture 3 - Data Representation 3 1. COSC 243 (Computer Architecture)

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

Welcome to the Primitives and Expressions Lab!

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

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Methods CSC 121 Fall 2016 Howard Rosenthal

Contents 10. Graphs of Trigonometric Functions

CS 312 Midterm 1 Spring 2013

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

Nested Loops. A loop can be nested inside another loop.

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

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

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

Building Java Programs

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

To graph the point (r, θ), simply go out r units along the initial ray, then rotate through the angle θ. The point (1, 5π 6

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

Methods CSC 121 Spring 2017 Howard Rosenthal

Introduction to Computer Programming

Topic 4 Expressions and variables

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

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Transcription:

Building Java Programs Chapter 3 Lecture 7: Return values, Math, and casting reading: 3.2, 2.1-2.2 (Slides adapted from Stuart Reges, Hélène Martin, and Marty Stepp) Copyright 2011 by Pearson Education

2

Projectile problem Write a program that displays (as text and graphics) the paths of projectiles thrown at various velocities and angles. Projectile #1: velocity = 60, angle = 50, steps = 10 Projectile #2: velocity = 50, angle = 80, steps = 50 step x y time 0 0.00 0.00 0.00 1 36.14 38.76 0.94 2 72.28 68.91 1.87 3 108.42 90.45 2.81 4 144.56 103.37 3.75 5 180.70 107.67 4.69 6 216.84 103.37 5.62 7 252.98 90.45 6.56 8 289.12 68.91 7.50 9 325.26 38.76 8.43 10 361.40 0.00 9.37 step x y time 0 0.00 0.00 0.00 1 1.74 9.69 0.20 2 3.49 18.98 0.40... 3

Java's Math class Method name Math.abs(value) Math.ceil(value) Math.floor(value) 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... 4

No output? Simply calling these methods produces no visible result. Math.pow(3, 4); // no output Math method calls use a Java 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 5

Return return: To send out a value as the result of a 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. (Compare to parameters which send values into a method) -42 Math.abs(-42) main 42 2.71 3 Math.round(2.71) 6

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); 7

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? 8

Quirks of real numbers Some Math methods return double or other non-int types. int x = Math.pow(10, 3); // ERROR: incompat. types Some double values print poorly (too many digits). double result = 1.0 / 3.0; System.out.println(result); // 0.3333333333333 The computer represents doubles in an imprecise way. System.out.println(0.1 + 0.2); Instead of 0.3, the output is 0.30000000000000004 9

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 10

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; 11

Returning a value 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 12

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); 13

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, 0, 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; 14

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; 15

Projectile problem Write a program that displays (as text and graphics) the paths of projectiles thrown at various velocities and angles. Projectile #1: velocity = 60, angle = 50, steps = 10 Projectile #2: velocity = 50, angle = 80, steps = 50 step x y time 0 0.00 0.00 0.00 1 36.14 38.76 0.94 2 72.28 68.91 1.87 3 108.42 90.45 2.81 4 144.56 103.37 3.75 5 180.70 107.67 4.69 6 216.84 103.37 5.62 7 252.98 90.45 6.56 8 289.12 68.91 7.50 9 325.26 38.76 8.43 10 361.40 0.00 9.37 step x y time 0 0.00 0.00 0.00 1 1.74 9.69 0.20 2 3.49 18.98 0.40... 16

Time observations We are given the number of "steps" of time to display. We must figure out how long it takes the projectile to hit the ground, then divide this time into the # of steps requested. step x y time 0 0.00 0.00 0.00 1 36.14 38.76 0.94 2 72.28 68.91 1.87... 10 361.40 0.00 9.37 Total time is based on the force of gravity on the projectile. Force of gravity (g) 9.81 m/s 2, downward The projectile has an initial upward velocity, which is fought by gravity until the projectile reaches its peak, then it falls. 17

Velocity and acceleration The projectile has a given initial velocity v 0, which can be divided into x and y components. v 0x = v 0 cos Θ v 0y = v 0 sin Θ Example: If v 0 =13 and Θ=60, v 0x =12 and v 0y =5. v 0 Θ v 0x v 0y The velocity v t of a moving body at time t, given initial velocity v 0 and acceleration a, can be expressed as: v t = v 0 + a t In our case, because of symmetry, at the end time t the projectile is falling exactly as fast as it was first going up. v t = -v 0 -v 0 = v 0 + a t t = -2 v 0 / a 18

X/Y position, displacement Based on the previous, we can now display x and time. x t = v x t since there is no force in the x direction. step x y time 0 0.00???? 0.00 1 36.14???? 0.94 2 72.28???? 1.87... 10 361.40???? 9.37 To display the y, we need to compute the projectile's displacement in y direction at each time increment. y t = v 0y t + ½ a t 2 Since this formula is complicated, let's make it into a method. 19

System.out.printf an advanced command for printing formatted text System.out.printf("format string", parameters); A format string contains placeholders to insert parameters into it: %d an integer %f a real number %s a string Example: int x = 3; int y = 2; System.out.printf("(%d, %d)\n", x, y); // (3, 2) 20

System.out.printf cont'd A placeholder can specify the parameter's width or precision: %8d an integer, 8 characters wide, right-aligned %-8d %.4f %6.2f an integer, 8 characters wide, left-aligned a real number, 4 characters after decimal a real number, 6 characters wide, 2 after decimal Examples: int age = 45; double gpa = 1.2345678; System.out.printf("%-8d %4f\n", age, gpa); System.out.printf("%8.3f %.1f %.5f", gpa, gpa, gpa); Output: 45 1.23 1.234 1.2 1.23457 21

Projectile solution // This program computes and draws the trajectory of a projectile. import java.awt.*; public class Projectile { // constant for Earth's gravity acceleration in meters/second^2 public static final double ACCELERATION = -9.81; public static void main(string[] args) { DrawingPanel panel = new DrawingPanel(420, 250); Graphics g = panel.getgraphics(); // v0 angle steps table(g, 60, 50, 10); g.setcolor(color.red); table(g, 50, 80, 50); // returns the displacement for a body under acceleration public static double displacement(double v0, double t, double a) { return v0 * t + 0.5 * a * t * t;... 22

Projectile solution... // prints a table showing the trajectory of an object given // its initial velocity v and angle and number of steps public static void table(graphics g, double v0, double angle, int steps) { double v0x = v0 * Math.cos(Math.toRadians(angle)); double v0y = v0 * Math.sin(Math.toRadians(angle)); double totaltime = -2.0 * v0y / ACCELERATION; double dt = totaltime / steps; System.out.println(" step x y time"); for (int i = 0; i <= steps; i++) { double time = i * dt; double x = i * v0x * dt; double y = displacement(v0y, time, ACCELERATION); System.out.printf("%8d%8.2f%8.2f%8.2f\n", i, x, y, time); g.filloval((int) x, (int) (250 - y), 5, 5); 23