Topic 11 Scanner object, conditional execution

Similar documents
Topic 11 Scanner object, conditional execution

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

Building Java Programs

CS 112 Introduction to Programming

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

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

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

Returns & if/else. Parameters and Objects

Building Java Programs

Building Java Programs

Topic 12 more if/else, cumulative algorithms, printf

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

Topic 12 more if/else, cumulative algorithms, printf

CSS 161 Fundamentals of Compu3ng. Flow control (2) October 10, Instructor: Uma Murthy

Lecture 4: Conditionals

Building Java Programs

Building Java Programs

Building Java Programs Chapter 4

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs Chapter 3

! 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

Advanced if/else & Cumulative Sum

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

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Topic 21 arrays - part 1

Building Java Programs

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

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

Chapter 2: Basic Elements of Java

Building Java Programs

Reading Input from Text File

Midterm Examination (MTA)

Chapter 4: Control Structures I

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

Java I/O and Control Structures

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Topic 13 procedural design and Strings

Building Java Programs

Building Java Programs

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Fundamentals of Programming Data Types & Methods

Java I/O and Control Structures Algorithms in everyday life

Building Java Programs

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Building Java Programs

Input. Scanner keyboard = new Scanner(System.in); String name;

Lecture 8 " INPUT " Instructor: Craig Duckett

Building Java Programs

Topic 14 while loops and loop patterns

H212 Introduction to Software Systems Honors

Chapter 4: Conditionals and Recursion

Computational Expression

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

AP Computer Science Unit 1. Programs

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

Using Java Classes Fall 2018 Margaret Reid-Miller

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CS 112 Introduction to Programming

Full file at

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

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

Selection and Repetition Revisited

Building Java Programs

A+ Computer Science -

Building Java Programs

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Selection and Repetition Revisited

AP Computer Science. File Input with Scanner. Copyright 2010 by Pearson Education

Bjarne Stroustrup. creator of C++

CS 106A, Lecture 25 Life After CS 106A, Part 1

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Text User Interfaces. Keyboard IO plus

Topic 4 Expressions and variables

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Selection Statements and operators

CSC 1051 Data Structures and Algorithms I

Type boolean. Building Java Programs. Recap: Type boolean. "Short-circuit" evaluation. De Morgan's Law. Boolean practice questions.

CSC 1051 Data Structures and Algorithms I

Topic 16 boolean logic

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

AP Computer Science Unit 1. Writing Programs Using BlueJ

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Object Oriented Programming. Java-Lecture 1

Introduction to Java Unit 1. Using BlueJ to Write Programs

2.2 - Making Decisions

CSCI 1103: File I/O, Scanner, PrintWriter

Text processing. Readings: 4.4

Building Java Programs Chapter 5

Building Java Programs Chapter 6

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

Data Conversion & Scanner Class

St. Edmund Preparatory High School Brooklyn, NY

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

CS 106 Introduction to Computer Science I

Building Java Programs

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Transcription:

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

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 Method nextint() nextdouble() nextline() next() Description reads an int from the user and returns it reads a double from the user reads a one-line String from the user reads a one-word String from the user Avoid when Scanner connected to System.in 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);

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

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. 2 B. 6 C. 7 D. 8 E. 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: Operator Meaning Example Value == equals 1 + 1 == 2 true!= does not equal 3.2!= 2.5 true < less than 10 < 5 false > greater than 10 > 5 true <= less than or equal to 126 <= 100 false >= greater than or equal to 5.0 >= 5.0 true

Logical operators Tests can be combined using logical operators: Operator Description Example Result && and (2 == 3) && (-1 < 5) false or (2 == 3) (-1 < 5) true! not!(2 == 3) true "Truth tables" for each, used with logical values p and q: p q p && q p q true true true true true false false true false true false true false false false false p!p true false false 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 returns the largest of three numbers using if statements 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 = 1 + 2 + 3, perfect 8 > 1 + 2 + 4, deficient 12 < 1 + 2 + 3 + 4 + 6, 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