Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 7: Input and Miscellaneous

Similar presentations


Presentation on theme: "Lecture 7: Input and Miscellaneous"— Presentation transcript:

1 Lecture 7: Input and Miscellaneous
Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.

2 Interactive Programs with Scanner

3 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, ...

4 Scanner syntax 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);

5 Scanner methods prompt: A message telling the user what input to type.
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.

6 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 "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) ...

7 Scanner example 2 Output (user input underlined):
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. It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line.

8 Scanner example Console (user input underlined): age 29 years 36
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(); int years = 65 - age; System.out.println(years + " years to retirement!"); } Console (user input underlined): How old are you? 36 years until retirement! age 29 years 36 It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line. 29

9 Strings as user input Scanner's next method reads a word of input as a String. Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); System.out.println(“Your name is “ + name + “.”); Output: What is your name? Matthew Your name is Matthew. The nextLine method reads a line of input as a String. System.out.print("What is your address? "); String address = console.nextLine();

10 Escape Sequences

11 Escape sequences escape sequence: A special sequence of characters used to represent certain special characters in a string. \t tab character \n new line character \" quotation mark character \\ backslash character Example: System.out.println("\\hello\nhow\tare \"you\"?\\\\"); Output: \hello how are "you"?\\

12 Questions What is the output of the following println statements?
System.out.println("\ta\tb\tc"); System.out.println("\\\\"); System.out.println("'"); System.out.println("\"\"\""); System.out.println("C:\nin\the downward spiral"); Output of each println statement: a b c \\ ' """ C: in he downward spiral

13 Questions Write a println statement to produce this output:
/ \ // \\ /// \\\ println statement to produce the line of output: System.out.println("/ \\ // \\\\ /// \\\\\\");

14 Questions What println statements will generate this output?
This program prints a quote from the Gettysburg Address. "Four score and seven years ago, our 'fore fathers' brought forth on this continent a new nation.” println statements to generate the output: System.out.println("This program prints a"); System.out.println("quote from the Gettysburg Address."); System.out.println(); System.out.println("\"Four score and seven years ago,"); System.out.println("our 'fore fathers' brought forth on"); System.out.println("this continent a new nation.\"");

15 Questions What println statements will generate this output?
A "quoted" String is 'much' better if you learn the rules of "escape sequences." Also, "" represents an empty String. Don't forget: use \" instead of " ! '' is not the same as ” println statements to generate the output: System.out.println("A \"quoted\" String is"); System.out.println("'much' better if you learn"); System.out.println("the rules of \"escape sequences.\""); System.out.println(); System.out.println("Also, \"\" represents an empty String."); System.out.println("Don't forget: use \\\" instead of \" !"); System.out.println("'' is not the same as \"");

16 nextLine glitch Using nextLine() after nextInt(), next() or nextDouble() produces a little glitch. Scanner input=new Scanner(System.in); System.out.println(“Enter a number:”); int num=input.nextInt(); System.out.println(“Enter first string:”); String str1=input.nextLine(); System.out.println(“Enter second string:”); String str2=input.nextLine();

17 Output Output: Enter a number: 3 //user enters 3 and presses enter
Enter first string: //program is supposed stop here for input //but is skipped. Enter second string: //program waits here for input Note: The first nextLine() consumes the \n character when the user presses enter.

18 Fixed Scanner input=new Scanner(System.in);
System.out.println(“Enter a number:”); int num=input.nextInt(); input.nextLine() //to consume the /n character System.out.println(“Enter first string:”); String str1=input.nextLine(); System.out.println(“Enter second string:”); String str2=input.nextLine();

19 Fencepost Problem

20 A deceptive problem... Write a method printNumbers that prints each number from 1 to a given maximum, separated by commas. For example, the call: printNumbers(5) should print: 1, 2, 3, 4, 5

21 Flawed solutions Output from printNumbers(5): 1, 2, 3, 4, 5,
public static void printNumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(i + ", "); } System.out.println(); // to end the line of output Output from printNumbers(5): 1, 2, 3, 4, 5, System.out.print(", " + i); Output from printNumbers(5): , 1, 2, 3, 4, 5

22 Fence post analogy We print n numbers but need only n - 1 commas.
Similar to building a fence with wires separated by posts: If we use a flawed algorithm that repeatedly places a post + wire, the last post will have an extra dangling wire. for (length of fence) { place a post. place some wire. }

23 Fencepost loop Add a statement outside the loop to place the initial "post." Also called a fencepost loop or a "loop-and-a-half" solution. place a post. for (length of fence - 1) { place some wire. }

24 Fencepost method solution
public static void printNumbers(int max) { System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line Alternate solution: Either first or last "post" can be taken out: for (int i = 1; i <= max - 1; i++) { System.out.print(i + ", "); System.out.println(max); // to end the line

25 Sentinel values sentinel: A value that signals the end of user input.
sentinel loop: Repeats until a sentinel value is seen. Example: Write a program that prompts the user for numbers until the user types 0, then outputs their sum. (In this case, 0 is the sentinel value.) Enter a number (0 to quit): 10 Enter a number (0 to quit): 20 Enter a number (0 to quit): 30 Enter a number (0 to quit): 0 The sum is 60

26 Flawed sentinel solution
What's wrong with this solution? Scanner console = new Scanner(System.in); int sum = 0; int number = 1; // "dummy value", anything but 0 while (number != 0) { System.out.print("Enter a number (0 to quit): "); number = console.nextInt(); sum = sum + number; } System.out.println("The total is " + sum);

27 Changing the sentinel value
Modify your program to use a sentinel value of -1. Example log of execution: Enter a number (-1 to quit): 15 Enter a number (-1 to quit): 25 Enter a number (-1 to quit): 10 Enter a number (-1 to quit): 30 Enter a number (-1 to quit): -1 The total is 80

28 Changing the sentinel value
To see the problem, change the sentinel's value to -1: Scanner console = new Scanner(System.in); int sum = 0; int number = 1; // "dummy value", anything but -1 while (number != -1) { System.out.print("Enter a number (-1 to quit): "); number = console.nextInt(); sum = sum + number; } System.out.println("The total is " + sum); Now the solution produces the wrong output. Why? The total was 79

29 The problem with our code
Our code uses a pattern like this: sum = 0. while (input is not the sentinel) { prompt for input; read input. add input to the sum. } On the last pass, the sentinel -1 is added to the sum: prompt for input; read input (-1). add input (-1) to the sum. This is a fencepost problem. Must read N numbers, but only sum the first N-1 of them.

30 A fencepost solution sum = 0. prompt for input; read input. // place a "post" while (input is not the sentinel) { add input to the sum. // place a "wire" } Sentinel loops often utilize a fencepost "loop-and-a-half" style solution by pulling some code out of the loop.

31 Correct sentinel code Scanner console = new Scanner(System.in);
int sum = 0; // pull one prompt/read ("post") out of the loop System.out.print("Enter a number (-1 to quit): "); int number = console.nextInt(); while (number != -1) { sum = sum + number; // moved to top of loop number = console.nextInt(); } System.out.println("The total is " + sum);

32 Modified BMI With Input
Formula for body mass index (BMI): Write a program that produces output like the following: Enter your info. height (in inches): 70.0 weight (in pounds): BMI = overweight BMI Weight class below 18.5 underweight [18.5 – 25) normal [25.0 – 30) overweight 30.0 and up obese // This program computes two people's body mass index (BMI) and // compares them. The code uses parameters, returns, and Scanner. import java.util.*; // so that I can use Scanner public class BMI { public static void main(String[] args) { System.out.println("This program reads in data for two people and"); System.out.println("computes their body mass index (BMI)"); System.out.println(); // finish me! }

33 Modified PrintPrimes Modify your method printPrimes so that commas are correctly placed to solve the fencepost problem. Example: printPrimes(50) prints 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 If the maximum is less than 2, print no output.

34 Extract Digits Write method sumDigits which accepts a non-negative integer and returns the sum of its digits. sumDigits(12); // returns 3 since 1+2=3 sumDigits(1346); //returns 14 since =14 sumDigits( ); //returns 25 Hint: Consider integer dividing by 10 vs modulo dividing by 10.

35 Exam 2 Review Know how to trace for/while loops.
Know how to write for/while loops. Know how to evaluate Math class methods. Know how to generate real numbers and integers in a certain range using Math.random(). Know how to using for/while loops to write basic algorithms. Specifically, the difference between “definite”(for) and “indefinite”(while) loops. (e.g., multipleOf3, fourHeads, printTwoDigits, etc…) Know how to use helper methods to solve a problem. (e.g., use countFactors to write isPrime.) At minimum, you should be able to do problems from all 3 worksheets and write methods that are similar to the lab assignments(fourHeads, etc…)

36 Exam 2: Perfect Numbers First four perfect numbers: 6,28,496,8128.
A number n is perfect if it is equals to the sum of its factors excluding n itself. For example, 6 has factors 1,2,3,6 and 6= Thus 6 is perfect. Factors of 8 are 1,2,4,8 but 8 ≠ Thus 8 is not perfect. Factors of 28 are 1,2,4,7,14,28 and 28= Thus 28 is perfect. First four perfect numbers: 6,28,496,8128. Fifth perfect number is 33,550,336. No odd perfect numbers have been found.


Download ppt "Lecture 7: Input and Miscellaneous"

Similar presentations


Ads by Google