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

Similar documents
AP Computer Science A. Return values

Building Java Programs

Building Java Programs

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

Lecture 6: While Loops and the Math Class

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs

Building Java Programs Chapter 3

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

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

Topic 11 Scanner object, conditional execution

Building Java Programs

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Topic 12 more if/else, cumulative algorithms, printf

Topic 11 Scanner object, conditional execution

Building Java Programs

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

CS 112 Introduction to Programming

CSc 110, Spring Lecture 11: return values and math

Building Java Programs

AP CS Java Syntax Summary: (version 3)

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

4. Java Project Design, Input Methods

CSc 110, Autumn Lecture 10: return values and math

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Introduction to Computer Science Unit 2. Notes

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

AP CS Unit 3: Control Structures Notes

AP CS Java Syntax Summary: (version 4)

CS110: PROGRAMMING LANGUAGE I

Introduction to Computer Science Unit 2. Notes

Important Java terminology

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

AP Computer Science Unit 1. Programs

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

Building Java Programs

CIS133J. Working with Numbers in Java

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

Building Java Programs

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

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

What did we talk about last time? Examples switch statements

Introduction to Java Unit 1. Using BlueJ to Write Programs

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

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

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

Chapter 5 Methods / Functions

AP Computer Science Unit 1. Writing Programs Using BlueJ

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

Advanced Object Concepts

Chapter 4: Control Structures I

Chapter 4: Conditionals and Recursion

Calculations, Formatting and Conversions

Full file at

STUDENT LESSON A7 Simple I/O

Data Conversion & Scanner Class

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

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

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Computational Expression

AP CS Java Syntax Summary: (version 5)

Java API: Math, Wrapper Classes, StringBuffer Random Data Quiz2

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

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

Midterm Examination (MTA)

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

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

Programming Exercise 7: Static Methods

Elementary Programming

Building Java Programs

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Chapter 6 Methods. Dr. Hikmat Jaber

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan


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

Computational Expression

Using Java Classes Fall 2018 Margaret Reid-Miller

ECE 122 Engineering Problem Solving with Java

Chapter 4 Mathematical Functions, Characters, and Strings

A Balanced Introduction to Computer Science, 3/E

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Java Classes: Math, Integer A C S L E C T U R E 8

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

Computer Programming I - Unit 2 Lecture 1 of 13

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

Module 4: Characters, Strings, and Mathematical Functions

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Reading Input from Text File

CT 229 Java Syntax Continued

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

Chapter 2: Basic Elements of Java

CEN 414 Java Programming

double float char In a method: final typename variablename = expression ;

A token is a sequence of characters not including any whitespace.

Transcription:

AP Computer Science Return values, Math, and double

Distance between points Write a method that given x and y coordinates for two points prints the distance between them If you can t do all of it, pseudocode? What?! You don t remember the distance formula?! 2

Java libraries Java comes with lots of goodies Graphics Color Math Learn more from the Application Programming Interface Linked from desktop http://download-llnw.oracle.com/javase/6/docs/api/index.html 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) larger of two values smaller of two values Math.pow(base, exp) 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. 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) 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

Interactive Programs with Scanner

Interactive programs interactive program: Reads input from the console. While the program runs, it asks the user to type input. The input typed by the user is stored in variables in the code. Can be tricky; users are unpredictable and misbehave. But interactive programs have more interesting behavior. 13

Scanner Scanner: An object that can read input from many sources. Communicates with System.in Can also read from files (Ch. 6), web sites, databases, The Scanner class is found in the java.util package. import java.util.*; // so you can use Scanner Constructing a Scanner object to read console input: Scanner name = new Scanner(System.in); Example: Scanner console = new Scanner(System.in); 14

Scanner methods Method nextint() nextdouble() next() nextline() Description reads an int from the user and returns it reads a double from the user reads a one-word String from the user reads a one-line String from the user Each method waits until the user presses Enter. The value typed by the user is returned. prompt System.out.print("How old are you? "); // int age = console.nextint(); System.out.println("You typed " + age); prompt: A message telling the user what input to type. 15

Scanner example import java.util.*; // so that I can use Scanner public class UserInputExample { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("How old are you? "); int age = console.nextint(); age 29 years 36 } } int years = 65 - age; System.out.println(years + " years until retirement!"); Console (user input underlined): How old are you? 29 36 years until retirement! 16

Scanner example 2 import java.util.*; // so that I can use Scanner public class ScannerMultiply { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("Please type two numbers: "); int num1 = console.nextint(); int num2 = console.nextint(); } } int product = num1 * num2; System.out.println("The product is " + product); Output (user input underlined): Please type two numbers: 8 6 The product is 48 The Scanner can read multiple values from one line. 17

Input tokens token: A unit of user input, as read by the Scanner. Tokens are separated by whitespace (spaces, tabs, new lines). How many tokens appear on the following line of input? 23 John Smith 42.0 "Hello world" $2.50 " 19" When a token is not the type you ask for, it crashes. System.out.print("What is your age? "); int age = console.nextint(); Output: What is your age? Zan java.util.inputmismatchexception at java.util.scanner.next(unknown Source) at java.util.scanner.nextint(unknown Source)... 18

Scanners as parameters If many methods need to read input, declare a Scanner in main and pass it to the other methods as a parameter. public static void main(string[] args) { Scanner console = new Scanner(System.in); readsum3(console); } // Prompts for 3 numbers and returns their sum. public static int readsum3(scanner console) { System.out.print("Type 3 numbers: "); int num1 = console.nextint(); int num2 = console.nextint(); int num3 = console.nextint(); System.out.println("The sum is " + sum); } 19