Topic 11 Scanner object, conditional execution



Similar documents
Building Java Programs

Building Java Programs

Building Java Programs

Introduction to Java

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Chapter 2: Elements of Java

Building Java Programs

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Basics of Java Programming Input and the Scanner class

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

AP Computer Science File Input with Scanner

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Chapter 2 Introduction to Java programming

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Sample CSE8A midterm Multiple Choice (circle one)

Install Java Development Kit (JDK) 1.8

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

6.1. Example: A Tip Calculator 6-1

Using Files as Input/Output in Java 5.0 Applications

13 File Output and Input

Line-based file processing

Topic 16 boolean logic

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Week 1: Review of Java Programming Basics

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Comp 248 Introduction to Programming

Building Java Programs

Introduction to Java. CS 3: Computer Programming in Java

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

JAVA ARRAY EXAMPLE PDF

LOOPS CHAPTER CHAPTER GOALS

Part I. Multiple Choice Questions (2 points each):

J a v a Quiz (Unit 3, Test 0 Practice)

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Chapter 3. Input and output. 3.1 The System class

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Visit us at

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Object-Oriented Programming in Java

CS 121 Intro to Programming:Java - Lecture 11 Announcements

CS 106 Introduction to Computer Science I

JAVA.UTIL.SCANNER CLASS

Arrays. Introduction. Chapter 7

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Programming in Java. What is in This Chapter? Chapter 1

Programming and Data Structures with Java and JUnit. Rick Mercer

The following program is aiming to extract from a simple text file an analysis of the content such as:

Building Java Programs

Some Scanner Class Methods

AP Computer Science Static Methods, Strings, User Input

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Introduction to Programming

Unit 6. Loop statements

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

D06 PROGRAMMING with JAVA

Chapter 2 Basics of Scanning and Conventional Programming in Java

Programming Languages CIS 443

Building Java Programs

Chapter 2 Elementary Programming

Example of a Java program

Interactive Programs and Graphics in Java

(Eng. Hayam Reda Seireg) Sheet Java

Chapter 8 Selection 8-1

Course Intro Instructor Intro Java Intro, Continued

Data Structures Lecture 1

Moving from CS 61A Scheme to CS 61B Java

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Introduction to Java Lecture Notes. Ryan Dougherty

Conditionals (with solutions)

Object Oriented Software Design

Programming in Java Course Technology, a part of Cengage Learning.

CSE 8B Midterm Fall 2015

Arrays in Java. Working with Arrays

Lecture 1 Introduction to Java

Homework/Program #5 Solutions

More on Objects and Classes

Conditional Statements Summer 2010 Margaret Reid-Miller

Event-Driven Programming

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

2009 Tutorial (DB4O and Visual Studio 2008 Express)

AP Computer Science Java Subset

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Lecture 5: Java Fundamentals III

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

AP Computer Science Java Mr. Clausen Program 9A, 9B

Building Java Programs

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

CSE 1020 Introduction to Computer Science I A sample nal exam

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 bu 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() Description reads an int from the user and returns it nextdouble() reads a double from the user next() nextline() 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: 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 prints out 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