CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson,

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs Lecture 3-3: Interactive Programs w/
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
1 CSE 142 Lecture Notes Interactive Programs with Scanner Chapter 4 Suggested reading: Suggested self-checks: Section 4.10 #1-4 These lecture.
1 Scanner objects. 2 Interactive programs We have written programs that print console output. It is also possible to read input from the console.  The.
Topic 11 Scanner object, conditional execution Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University.
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Objects and Classes; Strings. 2 Classes and objects class: A program entity that represents either 1.A program / module, or 2.A type of objects* –A class.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
CS 112 Introduction to Programming Graphics; Animation Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Interactive Programs with Scanner. 2 Input and System.in interactive program: Reads input from the console. –While the program runs, it asks the user.
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.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
CS 112 Introduction to Programming Variable Scoping; Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
Copyright 2010 by Pearson Education Building Java Programs Scanner ; if / else; while loops ; random reading: 3.3 – 3.4, 4.1, 4.5, 5.1, 5.6.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Copyright 2010 by Pearson Education Building Java Programs Chapter 3 Lecture 3-1: Parameters reading: 3.1.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Building Java Programs Chapter 4 Lecture 4-1: Scanner ; cumulative algorithms reading: 3.3 – 3.4, 4.2.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
CS 112 Introduction to Programming Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Java Graphics Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Summary of Method Definition and Invocation; printf/format Formatting Yang (Richard) Yang Computer Science Department.
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.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Building Java Programs
Variables in Java A variable holds either
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
CSCI 161 – Introduction to Programming I William Killian
Yanal Alahmad Java Workshop Yanal Alahmad
Building Java Programs
Topic 11 Scanner object, conditional execution
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 – 3.4, 4.1, 4.5
Building Java Programs
Building Java Programs
Optional Topic: User Input with Scanner
Presentation transcript:

CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Admin  PS4 m Part 1: speed and angle interpretation m Walkthroughs Monday and Tuesday evenings  Debugging session: m Please contribute buggy code to us  Puzzle Day: Feb. 21-Feb. 24.  Midterm 1 date: Mar. 3 2

vertical retrace Recap: StdDraw.show(T) Display Draw ADraw BDraw C Buffer Display Draw ADraw BDraw C TT

Recap: General Method Definition public static type name ( parameters ) { statements ;... return expression ; } methodname returntype parameter list properties

5 Summary: Method Definition  Why define methods? m Denote structure, eliminate redundancy m A method with parameters solves an entire class of similar problems  Can you define in the same class multiple methods with the same name? m Yes. This is called method overloading, as long as the overloaded methods must have different signatures, where the signature of a method is the sequential list of the type of each parameter

6 Summary: Method Invocation (I)  How does the compiler pick the method to use for overloaded methods? m The compiler picks the method according to signature match. double tryMe (int x) { return x +.375; } Version 1: signature: int double tryMe (double x, double y) { return x * y; } Version 2: signature: double_double result = tryMe (25, 4.32)Invocation double tryMe (double x, int y) { return x * y; } Version 3: signature: double_int

7 Summary: Method Invocation (II)  Corresponding actual argument in the invocation is assigned to the corresponding formal argument public static void printNumber(int number, int count) { for (int i = 1; i <= count; i++) { System.out.print(number); } System.out.println(); } int line = 3; printNumber(line-1,5); // equiv: number = 2; count = 5;

8 Formal Arguments are Local Variables  In Java, a formal argument is a local variable of a method  The formal argument and the actual argument are different variables, with different memory locations, even if they have the same name.  When a primitive variable is passed as the actual argument to a formal argument, the value is copied m Value copying implies value semantic m Implication: modifying the parameter inside the method will not affect the variable passed in.

Value Semantics int a = 100; double x = 45.12; a x A value variable stores a value of the type of the variable.

10 Value Variables int a = 100; double x = 45.12; int aa; 100 a x aa

11 Value-Variable Assignment int a = 100; double x = 45.12; int aa; aa = a; 100 a x aa An assignment of one value variable to another value variable copies the value. 100

12 Value-Variable Assignment int a = 100; double x = 45.12; int aa; aa = a; a = 200; 100 a x aa 100 Change the value of one value variable will not change the other. 200

Exercise: What is the output? 13 public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); }

Example: main() start 14 public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); }

Example: Invocation 15 public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); } public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x x compiler declares formal argument x and copies value from the actual argument 23

Example: Local update 16 public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); } public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x 23 x 24

Example: Method return 17 public static void strange(int x) { x = x + 1; System.out.println("1. x = " + x); } public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x x compiler un-declares formal argument 24

Example: Method return 18 public static void main(String[] args) { int x = 23; strange(x); System.out.println("2. x = " + x); } 23 args x

A "Parameter Mystery" problem public class ParameterMystery { public static void main(String[] args) { int x = 9; int y = 2; int z = 5; mystery(z, y, x); mystery(y, x, z+y); } public static void mystery(int x, int z, int y) { System.out.println(z + " and " + (y - x)); } What is the output?

20 Summary: Return  The return type of a method indicates the type of value that the method sends back to the calling location  a method that does not return a value has a void return type  The return statement specifies the value that will be returned m its expression must conform to the return type

Foundational Programming Concepts 21 objects methods and classes graphics, sound, and image I/O arrays conditionals and loops Mathtext I/O assignment statementsprimitive data types any program you might want to write

Outline  Admin and recap  Text input using methods from the Scanner class 22

Interactive Programs  Interactive programs can be easier to use and have more interesting behavior  Interactive programs can be tricky: users are unpredictable and may misbehave.  Java text input is based on the Scanner class

Some Scanner Methods MethodDescription nextInt() Returns an int from source nextDouble() Returns a double from source next() Returns a one-word String from source nextLine() Returns a one-line String from source

Problem of using Scanner  It is common that the same program reads input simultaneously from multiple sources:  System.in (the opposite of System.out ) m Files, strings, web sites, databases,...

Design Option I Method Scanner.nextInt( ) Scanner.nextDouble( ) Scanner.next( ) Scanner.nextLine( )

Design Option II: Objects (briefly)  object: An entity that contains both data and behavior. m data variables inside the object m behavior methods offered by the object m You interact with the methods; most data are hidden in the object.

Constructing Objects  An object is created from a class  Constructing (creating) an object by calling the constructor method: Type objectName = new Type ( parameters );  Calling an object's method: objectName. methodName ( parameters );

29 Packages  The classes in Java are organized into packages m think of packages as folders, which help you to get organized  Some of the packages in Java are:  Scanner belongs to the java.util package Package java.lang java.applet java.awt javax.swing java.net java.util java.text Purpose General support, e.g., Math, String, System Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities Text processing

30 The import Declaration  When you want to use a class from a non-default /java.lang package, you could use its fully qualified class name, e.g., java.util.Scanner console; Or you can import the class, then just use the class name // put this at the very top of your program import java.util.Scanner; … Scanner console;  To import all classes in a particular package, you can use the * wildcard character // put this at the very top of your program import java.util.*;

Using Scanner import java.util.Scaner; … Scanner console = new Scanner(System.in); // Typically print a prompt System.out.print("How old are you? "); int age = console.nextInt(); System.out.println("You typed " + age);

32 Scanner for System.in  Using System.in is to interact using the Terminal:

Scanner Example import java.util.*; // so that I can use Scanner public class UserScannerInput { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print(”Which year will you graduate? "); int year = console.nextInt(); int rYears = year ; System.out.println(years + " years remaining at Yale!"); } }  Console (user input underlined): Which year will you graduate? 0 years remaining at Yale! 2014 year2014 rYears0 UserScannerInput.java

Scanner Example 2  The Scanner can read multiple values from one line. 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 ScannerMultiply.java

Scanning Details  The OS will not send input to Scanner constructed using System.in until user hits enter  nextInt(), nextDouble(), next() are token based scanning methods m skip whitespace (spaces, tabs, new lines) until find first non-white space, collect input into a token until a whitespace, send token to the method to interpret; the following white space remains m How many tokens appear on the following line of input? 23 John Smith 42.0 "Hello world" $2.50 " 19”  nextLine() collects any input character into a string until the first new line and discards the new line ScannerTokenDiff.java

Practice: Scanner Fun  Please try out ScannerFun.java 36 ScannerFun.java

Input from File  There are two approaches m Create a scanner with src as a file (more later)  Redirect a file as standard input (command line) %java PlotUSA < USA.txt PlotUSA.java USA.txt

Input from File PlotUSA.java USA.txt

Design Issue  What value to return when a token is not the type the scanner expects System.out.print("What is your age? "); int age = console.nextInt(); Output: What is your age? Timmy

Token and Exception  When a token is not the type that the scanner expects, since no reasonable (non- ambiguous) return value, Scanner throws an exception (panic) System.out.print("What is your age? "); int age = console.nextInt(); Output: What is your age? Timmy java.util.InputMismatchException at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source)...

Why Not a “Smarter” nextInt()  For example, continue to scan the input to find the integer?  Design principle: design of basic methods should KISS (Keep It Simple and Stupid) 41

Problem: How to avoid crash when user gives wrong input? 42

The if statement Executes a block of statements only if a test is true if ( test ) { statement ;... statement ; }  Example: if (grade >= 90.0 && grade <= 100) { System.out.println(”It is an A."); }

44 The if/else Statement  An else clause can be added to an if statement to make it an if-else statement: if ( test ) { statement1; } else { statement2; }  If the condition is true, statement1 is executed; if the condition is false, statement2 is executed  One or the other will be executed, but not both

The if/else Statement  Example: if (gpa >= 2.0 && gpa <= 3.8) { System.out.println("Welcome to Middle Univ.!"); } else { System.out.println("Application denied."); }

Backup Slides

Practice: Loan Calculator  Design a loan program to compute the monthly amortization table of a fixed-rate loan 47 Loan.java

Rules of Fixed-Rate Loan  Assume N periods (e.g., 120 months)  For each period, borrower pays interest on the remaining owed (principal) at the fixed rate  At the end of N’s period, the remaining principal goes to 0 48

Fixed-Rate Loan Calculation Alg.  Alg. focuses on owed (principal) Owed at initiation: Owed after 1 month: Owed after 2 month: Owed after 3 month:

Mapping Loop Variable Owed after N month: apply Owed after N month: Payoff loan after N month =>