Building Java Programs

Similar documents
Building Java Programs

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

Topic 11 Scanner object, conditional execution

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

Topic 11 Scanner object, conditional execution

Building Java Programs

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

Building Java Programs

Building Java Programs Chapter 4

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

CS 112 Introduction to Programming

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

Returns & if/else. Parameters and Objects

Topic 12 more if/else, cumulative algorithms, printf

Chapter 2: Basic Elements of Java

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

Building Java Programs

Building Java Programs

Building Java Programs

Topic 12 more if/else, cumulative algorithms, printf

Building Java Programs

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

Building Java Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs

Object Oriented Programming. Java-Lecture 1

Topic 13 procedural design and Strings

STUDENT LESSON A7 Simple I/O

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ

Building Java Programs

Building Java Programs

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Building Java Programs

Building Java Programs

Midterm Examination (MTA)

Chapter 4: Control Structures I

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

Building Java Programs

Building Java Programs Chapter 3

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

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

Full file at

Full file at

CS 112 Introduction to Programming

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

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

4 WORKING WITH DATA TYPES AND OPERATIONS

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

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

Building Java Programs Chapter 6

CSCI 1103: File I/O, Scanner, PrintWriter

Conditional Execution

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

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

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

Building Java Programs

Example: Monte Carlo Simulation 1

Reading Input from Text File

Console Input and Output

Building Java Programs

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Building Java Programs

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Computational Expression

Introduction to Computer Programming

COMP 202 Java in one week

Chapter 1 Lab Algorithms, Errors, and Testing

Building Java Programs

Example Program. public class ComputeArea {

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Chapter 3. Selections

Introduction to Java & Fundamental Data Types

Building Java Programs

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

Building Java Programs

First Java Program - Output to the Screen

Section 2.2 Your First Program in Java: Printing a Line of Text

Course Outline. Introduction to java

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Advanced if/else & Cumulative Sum

Full file at

Welcome to the Using Objects lab!

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

COMP 202. Java in one week

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Exercise (Revisited)

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

CSIS 10A Assignment 3 Due: 2/21 at midnight

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

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Transcription:

Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner 1

Lecture outline console input with Scanner objects input tokens Scanner as a parameter to a method cumulative sums and Scanner 2

Interactive programs using Scanner objects reading: 3.4 3

Interactive programs We have written programs that print console output. It is also possible to read input from the console. The user types the input into the console. We can capture the input and use it in our program. Such a program is called an interactive program. Interactive programs can be challenging: Computers and users think in very different ways. Users tend to misbehave. 4

System.out Input and System.in An object with methods named println and print System.in not intended to be used directly We use a second object, from a class Scanner, to help us. Constructing a Scanner object to read console input: Scanner <name> = new Scanner(System.in); Example: Scanner console = new Scanner(System.in); 5

Scanner methods Method nextint() nextdouble() next() Description reads user input as an int reads user input as a double reads user input as a String Each method waits until the user types input and presses Enter. The value typed 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'll be 40 in " + (40 - age) + " years."); 6

Java class libraries, import Java class libraries: Classes included with Java's JDK. organized into groups named packages To use a package, put an import declaration in your program. import declaration, general syntax: // put this at the very top of your program import <package name>.*; Scanner is in a package named java.util import java.util.*; 7

Example Scanner usage import java.util.*; // so that I can use Scanner public class ReadSomeInput { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("What is your first name? "); String name = console.next(); System.out.print("And how old are you? "); int age = console.nextint(); System.out.println(name + " is " + age); System.out.println("That's quite old!"); Output (user input underlined): What is your first name? Ruth How old are you? 14 Ruth is 14 That's quite old! 8

Another Scanner example import java.util.*; // so that I can use Scanner public class ScannerSum { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("Please type three numbers: "); int num1 = console.nextint(); int num2 = console.nextint(); int num3 = console.nextint(); int sum = num1 + num2 + num3; System.out.println("The sum is " + sum); Output (user input underlined): Please type three numbers: 8 6 13 The sum is 27 Notice that the Scanner can read multiple values from one line. 9

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. Example: System.out.print("What is your age? "); int age = console.nextint(); Output (user's input is underlined): What is your age? Timmy java.util.inputmismatchexception at java.util.scanner.throwfor(unknown Source) at java.util.scanner.next(unknown Source) at java.util.scanner.nextint(unknown Source)... 10

Scanners as parameters If many methods read input, declare a Scanner in main and pass it to the others as a parameter. All the methods share the same Scanner object. public static void main(string[] args) { Scanner console = new Scanner(System.in); int sum = readsum3(console); System.out.println("The sum is " + sum); // Prompts for 3 numbers and returns their sum. public static int readsum3(scanner console) { System.out.print("Type 3 numbers: "); int num1 = console.nextint(); int num2 = console.nextint(); int num3 = console.nextint(); return num1 + num2 + num3; 11

Scanner BMI question A person's body mass index (BMI) is computed by the following formula: = weight BMI height 703 2 Write a program that produces the following output: This program reads in data for two people and computes their body mass index (BMI) and weight status. Enter next person's information: height (in inches)? 62.5 weight (in pounds)? 130.5 Enter next person's information: height (in inches)? 58.5 weight (in pounds)? 90 Person #1 body mass index = 23.485824 Person #2 body mass index = 18.487836949375414 Difference = 4.997987050624587 12

Scanner BMI solution // This program computes two people's body mass index (BMI) // and compares them. The code uses parameters and returns. import java.util.*; // so that I can use Scanner public class BMI { public static void main(string[] args) { introduction(); Scanner console = new Scanner(System.in); double bmi1 = processperson(console); double bmi2 = processperson(console); // report overall results System.out.println("Person #1 body mass index = " + bmi1); System.out.println("Person #2 body mass index = " + bmi2); double difference = Math.abs(bmi1 - bmi2); System.out.println("Difference = " + difference); // prints a welcome message explaining the program public static void introduction() { System.out.println("This program reads in data for two people"); System.out.println("and computes their body mass index (BMI)"); System.out.println("and weight status."); System.out.println();... 13

Scanner BMI solution, cont.... // reads information for one person, computes their BMI, and returns it public static double processperson(scanner console) { System.out.println("Enter next person's information:"); System.out.print("height (in inches)? "); double height = console.nextdouble(); System.out.print("weight (in pounds)? "); double weight = console.nextdouble(); System.out.println(); double bmi = getbmi(height, weight); return bmi; // Computes a person's body mass index based on their height and weight // and returns the BMI as its result. public static double getbmi(double height, double weight) { double bmi = weight / (height * height) * 703; return bmi; 14

Types int and double Printing double values can be ugly: double result = 1.0 / 3.0; System.out.println(result); // 0.3333333333333 Can we print it with only 2 digits after the decimal? Rounding the number doesn't help: double result = 1.0 / 3.0; System.out.println(Math.round(result)); // 0 15

Rounding real numbers To round to N places: multiply by 10 N round divide by 10 N Example: double result = 1.0 / 3.0; // 0.333333333333 result = result * 100; // 33.333333333 result = Math.round(result); // 33.0 result = result / 100; // 0.33 System.out.println(result); 16

System.out.printf System.out.printf prints formatted text. System.out.printf("<format string>", <parameters>); The format string contains format placeholders to specify how to insert the parameters into the string. %d %f %s an integer a real number a string A format placeholder can specify a width: %8d %-8d %12f %.4f %6.2f an integer, 8 characters wide, right-aligned an integer, 8 characters wide, left-aligned a real number, 12 characters wide a real number, 4 characters after decimal a real number, 6 total characters wide, 2 after decimal Example: double d = 1.0 / 3.0; // 0.33333333333 System.out.printf("It's %8.2f\n", d); // It's 0.33 17

int x = 38, y = 152; int grade = 86; double angle = 87.4163; String veggie = "carrot"; printf examples System.out.printf("hello there\n"); System.out.printf("x=%d and y=%d\n", x, y); System.out.printf("score is %d%%\n", (grade + 5)); System.out.printf("oh my!%d!%6d%6d\n", grade, x, y); System.out.printf("huh? %.2f %16.5f\n", angle, angle); System.out.printf("%s%12s!%-8s!\n", veggie, veggie, veggie); Output: hello there x=38 and y=152 score is 91% oh my!86! 38 152 huh? 87.42 87.41630 carrot carrot!carrot! 18

Scanner and cumulative sum We can do a cumulative sum of user input: Scanner console = new Scanner(System.in); int sum = 0; for (int i = 1; i <= 100; i++) { System.out.print("Type a number: "); sum += console.nextint(); System.out.println("The sum is " + sum); 19

User-guided cumulative sum User input can control the number of loop repetitions: Desired example output: How many numbers to add? 3 Type a number: 2 Type a number: 6 Type a number: 3 The sum is 11 Answer: Scanner console = new Scanner(System.in); System.out.print("How many numbers to add? "); int count = console.nextint(); int sum = 0; for (int i = 1; i <= count; i++) { System.out.print("Type a number: "); sum += console.nextint(); System.out.println("The sum is " + sum); 20

Cumulative sum question Write a program that reads input of the number of hours two employees have worked and displays each employee's total and the overall total hours. The company doesn't pay overtime, so cap any day at 8 hours. Example log of execution: Employee 1: How many days? 3 Hours? 6 Hours? 12 Hours? 5 Employee 1's total hours = 19 Employee 2: How many days? 2 Hours? 11 Hours? 6 Employee 2's total hours = 14 Total hours for both = 33 21

Cumulative sum answer // Computes the total paid hours worked by two employees. // The company does not pay for more than 8 hours per day. // Uses a "cumulative sum" loop to compute the total hours. import java.util.*; public class Hours { public static void main(string[] args) { Scanner console = new Scanner(System.in); int hours1 = processemployee(console, 1); int hours2 = processemployee(console, 2); int total = hours1 + hours2; System.out.println("Total hours for both = " + total);... 22

Cumulative sum answer 2... // Reads hours information about one employee with the given number. // Returns the total hours worked by the employee. public static int processemployee(scanner console, int number) { System.out.print("Employee " + number + ": How many days? "); int days = console.nextint(); // totalhours is a cumulative sum of all days' hours worked. int totalhours = 0; for (int i = 1; i <= days; i++) { System.out.print("Hours? "); int hours = console.nextint(); totalhours += Math.min(hours, 8); // cap at 8 hours/day System.out.println("Employee " + number + "'s total hours = " + totalhours); System.out.println(); return totalhours; 23