Building Java Programs

Similar documents
AP Computer Science A. Return values

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

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

Lecture 6: While Loops and the Math Class

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

CSc 110, Spring Lecture 11: return values and math

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs Chapter 3

CSc 110, Autumn Lecture 10: return values and math

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

Building Java Programs

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

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

Building Java Programs

Building Java Programs

Garfield AP CS. Graphics

Topic 12 more if/else, cumulative algorithms, printf

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

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

Building Java Programs

AP CS Java Syntax Summary: (version 3)

Returns & if/else. Parameters and Objects

Building Java Programs

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

Topic 8 Graphics. Margaret Hamilton

Using Graphics. Building Java Programs Supplement 3G

CS110: PROGRAMMING LANGUAGE I

Topic 8 graphics. -mgrimes, Graphics problem report 134

AP CS Java Syntax Summary: (version 4)

Week 3. parameters, return, math, graphics

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.

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

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

CS 312 Midterm 1 Spring 2013

Chapter 5 Methods / Functions

CIS133J. Working with Numbers in Java

Introduction to Computer Science Unit 2. Notes

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

CS 312 Midterm 1 Spring 2013

Chapter 6 Methods. Dr. Hikmat Jaber

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

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

Computer Programming I - Unit 2 Lecture 1 of 13

AP CS Java Syntax Summary: (version 5)

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

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

Chapter 4 Mathematical Functions, Characters, and Strings

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

Introduction to Computer Science Unit 2. Notes

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

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

Building Java Programs

Building Java Programs

Calculations, Formatting and Conversions

Introduction to Computer Science and Object-Oriented Programming

Variables, Types, Operations on Numbers

Welcome to the Primitives and Expressions Lab!

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

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

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

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

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

AP CS Unit 3: Control Structures Notes

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

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

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

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

Solution Notes. COMP 151: Terms Test

Building Java Programs

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

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

Using Methods and Parameters

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

Math 144 Activity #2 Right Triangle Trig and the Unit Circle

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

Building Java Programs

Object Oriented Methods : Deeper Look Lecture Three

Building Java Programs

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

CSc 110, Autumn 2016 Lecture 7: Graphics. Adapted from slides by Marty Stepp and Stuart Reges

Chapter 2: Review Exercise Solutions R2.1

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

Important Java terminology

Advanced Object Concepts

CS 305j Midterm 1 Fall 2007

4. Java Project Design, Input Methods

Unit 5: Recursive Thinking

Lecture 2: Operations and Data Types

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


Transcription:

Building Java Programs Chapter 3 Lecture 3-2: Return; doubles and casting reading: 3.2, 4.1 videos: Ch. 3 #2 Copyright 2009 by Pearson Education

Finish Car example Lecture outline Returns Java Math library (using methods that return values) Writing methods that return values Casting (if time) Copyright 2009 by Pearson Education 2

Parameterized figures Modify the car-drawing method so that it can draw cars at different positions, as in the following image. Top-left corners: (10, 30), (150, 10) Copyright 2009 by Pearson Education 3

Parameterized answer import java.awt.*; public class Car3 { public static void main(string[] args) { DrawingPanel panel = new DrawingPanel(260, 100); panel.setbackground(color.light_gray); Graphics g = panel.getgraphics(); drawcar(g, 10, 30); drawcar(g, 150, 10); public static void drawcar(graphics g, int x, int y) { g.setcolor(color.black); g.fillrect(x, y, 100, 50); g.setcolor(color.red); g.filloval(x + 10, y + 40, 20, 20); g.filloval(x + 70, y + 40, 20, 20); g.setcolor(color.cyan); g.fillrect(x + 70, y + 10, 30, 20); Copyright 2009 by Pearson Education 4

Drawing parameter question Then modify drawcar so the car can be drawn at any size. Existing car: size 100 Second car: size 50, top/left at (150, 10) Copyright 2009 by Pearson Education 5

Drawing parameter answer import java.awt.*; public class Car4 { public static void main(string[] args) { DrawingPanel panel = new DrawingPanel(210, 100); panel.setbackground(color.light_gray); Graphics g = panel.getgraphics(); drawcar(g, 10, 30, 100); drawcar(g, 150, 10, 50); public static void drawcar(graphics g, int x, int y, int size) { g.setcolor(color.black); g.fillrect(x, y, size, size / 2); g.setcolor(color.red); g.filloval(x + size / 10, y + 2 * size / 5, size / 5, size / 5); g.filloval(x + 7 * size / 10, y + 2 * size / 5, size / 5, size / 5); g.setcolor(color.cyan); g.fillrect(x + 7 * size / 10, y + size / 10, 3 * size / 10, size / 5); Copyright 2009 by Pearson Education 6

Loops that begin at 0 Beginning at 0 and using < can make coordinates easier. Use a for loop to draw a line of cars. Start at (10, 130), each car size 40, separated by 50px. Copyright 2009 by Pearson Education 7

Looping answer import java.awt.*; public class Car5 { public static void main(string[] args) { DrawingPanel panel = new DrawingPanel(210, 100); panel.setbackground(color.light_gray); Graphics g = panel.getgraphics(); drawcar(g, 10, 30, 100); drawcar(g, 150, 10, 50); for (int i = 0; i < 5; i++) { drawcar(g, 10 + i * 50, 130, 40); public static void drawcar(graphics g, int x, int y, int size) { g.setcolor(color.black); g.fillrect(x, y, size, size / 2); g.setcolor(color.red); g.filloval(x + size / 10, y + 2 * size / 5, size / 5, size / 5); g.filloval(x + 7 * size / 10, y + 2 * size / 5, size / 5, size / 5); g.setcolor(color.cyan); g.fillrect(x + 7 * size / 10, y + size / 10, 3 * size / 10, size / 5); Copyright 2009 by Pearson Education 8

Drawing w/ loops questions Draw ten stacked rectangles starting at (20, 20), height 10, width starting at 100 and decreasing by 10 each time: DrawingPanel panel = new DrawingPanel(160, 160); Graphics g = panel.getgraphics(); for (int i = 0; i < 10; i++) { g.drawrect(20, 20 + 10 * i, 100-10 * i, 10); Copyright 2009 by Pearson Education 9

Return Values reading: 3.2 self-check: #7-11 exercises: #4-6 videos: Ch. 3 #2 Copyright 2009 by Pearson Education

Java's Math class Method name Math.abs(value) Math.round(value) Math.ceil(value) Math.floor(value) Description absolute value nearest whole number rounds up rounds down Math.log10(value) logarithm, base 10 Math.max(value1, value2) Math.min(value1, value2) Math.pow(base, exp) Math.sqrt(value) Math.sin(value) Math.cos(value) Math.tan(value) Math.toDegrees(value) Math.toRadians(value) larger of two values smaller of two values base to the exp power square root sine/cosine/tangent of an angle in radians convert degrees to radians and back Constant Description E 2.7182818... PI 3.1415926... Math.random() random double between 0 and 1 Copyright 2009 by Pearson Education 11

Calling Math methods Math.methodName(parameters) Examples: double squareroot = Math.sqrt(121.0); System.out.println(squareRoot); // 11.0 int absolutevalue = Math.abs(-50); System.out.println(absoluteValue); // 50 System.out.println(Math.min(3, 7) + 2); // 5 The Math methods do not print to the console. Each method produces ("returns") a numeric result. The results are used as expressions (printed, stored, etc.). Copyright 2009 by Pearson Education 12

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. -42 Math.abs(-42) main 42 2.71 3 Math.round(2.71) Copyright 2009 by Pearson Education 13

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? Copyright 2009 by Pearson Education 14

Returning a value public static type name(parameters) { statements;... 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; Copyright 2009 by Pearson Education 15

Return examples // Converts 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); Copyright 2009 by Pearson Education 16

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: // result not defined 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; Copyright 2009 by Pearson Education 17

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. public static void main(string[] args) { double ourslope = slope(0, 0, 6, 3); System.out.println("The slope is " + ourslope); 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; Copyright 2009 by Pearson Education 18

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 Copyright 2009 by Pearson Education 19

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 Copyright 2009 by Pearson Education 20

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 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; Copyright 2009 by Pearson Education 21

Return questions Write a method named area that accepts a circle's radius as a parameter and returns its area. You may wish to use the constant Math.PI in your solution. Write a method named attendance that accepts a number of lectures attended by a student, and returns how many points a student receives for attendance. The student receives 2 points for each of the first 5 lectures and 1 point for each subsequent lecture. Copyright 2009 by Pearson Education 22

Return questions 2 Write a method named distancefromorigin that accepts x and y coordinates as parameters and returns the distance between that (x, y) point and the origin. Write a method named medianof3 that accepts 3 integers as parameters and returns the middle value. For example, medianof3(4, 2, 7) should return 4. Hint: Use methods from the Math class in your solution. Copyright 2009 by Pearson Education 23