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

Similar documents
Topic 11 Scanner object, conditional execution

Building Java Programs

Topic 11 Scanner object, conditional execution

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

Returns & if/else. Parameters and Objects

Lecture 4: Conditionals

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

CS 112 Introduction to Programming

Building Java Programs

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

Topic 12 more if/else, cumulative algorithms, printf

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

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

Building Java Programs

Building Java Programs Chapter 4

Building Java Programs

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

CS 112 Introduction to Programming

Topic 12 more if/else, cumulative algorithms, printf

Building Java Programs

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

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

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs Chapter 3

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

Building Java Programs

Advanced if/else & Cumulative Sum

Building Java Programs

Chapter 4: Control Structures I

Building Java Programs

! 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

Chapter 2: Basic Elements of Java

Building Java Programs

Building Java Programs

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

Building Java Programs

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

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

Computational Expression

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

Lecture 8 " INPUT " Instructor: Craig Duckett

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

AP Computer Science Unit 1. Programs

CS 112 Introduction to Programming

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

Building Java Programs

Object Oriented Programming. Java-Lecture 1

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

Chapter 4: Conditionals and Recursion

Reading Input from Text File

Using Java Classes Fall 2018 Margaret Reid-Miller

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

AP Computer Science Unit 1. Writing Programs Using BlueJ

Building Java Programs

H212 Introduction to Software Systems Honors

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

Week 4. Strings, if/else, return, user input

Java I/O and Control Structures

Building Java Programs Chapter 5

Midterm Examination (MTA)

Fundamentals of Programming Data Types & Methods

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

2.2 - Making Decisions

Building Java Programs

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Building Java Programs

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

CS 106 Introduction to Computer Science I

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

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

AP CS Java Syntax Summary: (version 3)

Java I/O and Control Structures Algorithms in everyday life

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

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

Conditional Execution

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

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

Building Java Programs

A+ Computer Science -

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Example Program. public class ComputeArea {

Java Coding 3. Over & over again!

Question: Total Points: Score:

Building Java Programs Chapter 6

Building Java Programs

Computational Expression

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

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

Full file at

In this chapter, you will:

AP CS Java Syntax Summary: (version 4)

ECE 122 Engineering Problem Solving with Java

Lab 4. Java Concepts Lab 4

Introduction to Java Unit 1. Using BlueJ to Write Programs

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

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

Topic 21 arrays - part 1

Transcription:

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

Warmup Write a method add10 that takes one integer parameter. Your method should return the number passed in plus ten.

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 (the opposite of System.out) Can also read from files (Ch. 6), web sites, databases,...

Scannersyntax 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);

Scannermethods Method Description 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 Each method waits until the user presses Enter. The value typed by the user is returned. System.out.print("How old are you? "); // prompt int age = console.nextint(); System.out.println("You typed " + age); prompt: A message telling the user what input to type.

Scannerexample 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!

Scannerexample 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.

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? Timmy java.util.inputmismatchexception at java.util.scanner.next(unknown Source) at java.util.scanner.nextint(unknown Source)...

Conditionals Fundamental to creating complex behavior Especially useful when user input is involved React differently based on what they entered

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

The if/elsestatement Executes one block if a test is true, another if false else { 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 booleanexpressionsthat 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

Misuse of if What's wrong with the following code? Scanner console = new Scanner(System.in); System.out.print("What percentage did you earn? "); int percent = console.nextint(); if (percent >= 90) { System.out.println("You got an A!"); if (percent >= 80) { System.out.println("You got a B!"); if (percent >= 70) { System.out.println("You got a C!"); if (percent >= 60) { System.out.println("You got a D!"); if (percent < 60) { System.out.println("You got an F!");...

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

Nested if/else/if If it ends with else, exactly one path must be taken. If it ends with if, the code might not execute any path. else else Example: if (place == 1) { System.out.println("Gold medal!"); else if (place == 2) { System.out.println("Silver medal!"); else if (place == 3) { System.out.println("Bronze medal.");

Nested ifstructures exactly 1 path (mutually exclusive) else else { 0 or 1 path (mutually exclusive) else else 0, 1, or many paths (independent tests; not exclusive)

Which nested if/else? (1) if/if/if (2) nested if/else (3) nested if/else/if Whether a user is lower, middle, or upper-class based on income. (2) nested if / else if / else Whether you made the dean's list (GPA 3.8) or honor roll (3.5-3.8). (3) nested if / else if Whether a number is divisible by 2, 3, and/or 5. (1) sequential if / if / if Computing a grade of A, B, C, D, or F based on a percentage. (2) nested if / else if / else if / else if / else