Topic 11 Scanner object, conditional execution Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from

Slides:



Advertisements
Similar presentations
BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution.
Advertisements

Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
1 BUILDING JAVA PROGRAMS CHAPTER 4 CONDITIONAL EXECUTION.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs Lecture 3-3: Interactive Programs w/
Introduction to Computer Programming Decisions If/Else Booleans.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
CS305j Introduction to Computing While Loops 1 Topic 15 Indefinite Loops - While Loops "If you cannot grok [understand] the overall structure of a program.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
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.
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Conditionals (Cont’d). 2 Nested if/else question Formula for body mass index (BMI): Write a program that produces output like the following: This program.
CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University.
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.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Building Java Programs
Interactive Programs with Scanner. 2 Input and System.in interactive program: Reads input from the console. –While the program runs, it asks the user.
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.
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
1 CSE 142 Lecture Notes Conditional Execution with if Statements; Methods that Return Values (briefly) Chapters 3 and 4 Suggested reading: ;
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
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.
CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson,
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.
Copyright 2008 by Pearson Education 1 The if statement Executes a block of statements only if a test is true if ( test ) { statement ;... statement ; }
Copyright 2010 by Pearson Education The if/else statement reading: 4.1, 4.6.
CSc 110, Autumn 2016 Lecture 9: input ; if/else Adapted from slides by Marty Stepp and Stuart Reges.
CompSci 230 S Programming Techniques
Building Java Programs
Building Java Programs
CSCI 161 – Introduction to Programming I William Killian
Lecture 7: Input and Miscellaneous
Building Java Programs Chapter 4
Building Java Programs
Lecture 4: Conditionals
Topic 11 Scanner object, conditional execution
Building Java Programs
CSc 110, Spring 2017 Lecture 8: input; if/else
Building Java Programs Chapter 4
Building Java Programs
CSc 110, Autumn 2016 Lecture 9: input; if/else
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 Chapter 4
Building Java Programs
Building Java Programs
Building Java Programs
Optional Topic: User Input with Scanner
Presentation transcript:

Topic 11 Scanner object, conditional execution Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from " There are only two kinds of programming languages: those people always … [complain] about and those nobody uses." — Bjarne Stroustroup, creator of C++

Input and System.in  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.  Scanner : An object that can read input from many sources. –Communicates with System.in –Can also read from files (Ch. 6), web sites, databases,...

Scanner syntax  The Scanner class is found in the java.util package. import java.util.Scanner;  Constructing a Scanner object to read console input: Scanner name = new Scanner(System.in); –Example: Scanner console = new Scanner(System.in);

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

Scanner example import java.util.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(); int years = 65 - age; System.out.println(years + " years until retirement!"); } }  Console (user input underlined): How old are you? 36 years until retirement! 29 age29 years36

Scanner example 2  The Scanner can read multiple values from one line. import java.util.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

Input tokens (clicker question)  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" A.2B. 6C. 7 D. 8E. 9

input tokens  When a token is the wrong type, the program crashes. (runtime error) 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)...

The if/else statement reading: 4.1

The if statement Executes a block of statements only if a test is true if ( test ) { statement ;... statement ; }  Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Application accepted."); }

The if/else statement Executes one block if a test is true, another if false if ( test ) { statement(s) ; } else { statement(s) ; }  Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); } else { System.out.println("Application denied."); }

Relational expressions  if statements and for loops both use logical tests. for (int i = 1; i <= 10; i++) {... if (i <= 10) {... –These are boolean expressions, seen in Ch. 5.  Tests use relational operators: OperatorMeaningExampleValue == equals == 2true != does not equal 3.2 != 2.5true < less than 10 < 5false > greater than 10 > 5true <= less than or equal to 126 <= 100false >= greater than or equal to 5.0 >= 5.0true

Logical operators  Tests can be combined using logical operators:  "Truth tables" for each, used with logical values p and q: OperatorDescriptionExampleResult && and (2 == 3) && (-1 < 5)false || or (2 == 3) || (-1 < 5)true ! not !(2 == 3)true pqp && qp || q true false true falsetruefalsetrue false p !p!p truefalse true

Nested if/else Chooses between outcomes using many tests if ( test ) { statement(s) ; } else if ( test ) { statement(s) ; } else { statement(s) ; }  Example: if (x > 0) { System.out.println("Positive"); } else if (x < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); }

Exercises  Write a method that prints out if it is good weather to go for a bike ride. The weather is good if the temperature is between 40 degrees and 100 degrees inclusive unless it is raining, in which case the temperature must be between 70 degrees and 110 degrees inclusive  Write a method that prints out the largest of three numbers.  Write a method that determines if one day is before another day (given month and day)

Exercise  Prompt the user to enter two people's heights in inches. –Each person should be classified as one of the following: short(under 5'3") medium(5'3" to 5'11") tall(6' or over) –The program should end by printing which person is taller. Height in feet and inches: 5 7 You are medium. Height in feet and inches: 6 1 You are tall. Person #2 is taller than person #1.

Exercises  Write a method that asks a user for 3 numbers and returns true if the numbers are all distinct  Write a method that determines if a number is a perfect number. A perfect number equals the sum of its integer divisors, excluding itself 6= , perfect , excessive

Exercises  Write a method that determines if we have time to go out for lunch. Inputs are distance to restaurant, average walking speed, time required to finish meal, time available, expected cost of meal, and money available  times are expressed as whole number of minutes  money is expressed as a double