Building Java Programs Chapter 3 4 Interactive Programs
Building Java Programs Chapter 3 -4 Interactive Programs with Scanner Copyright (c) Pearson 2013. All rights reserved.
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, . . . 2
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); 3
Scanner methods Method next. Int() Description reads an int from the user and returns it next. Double() reads a double from the user next() reads a one-word String from the user next. Line() 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. next. Int(); System. out. println("You typed " + age); • prompt: A message telling the user what input to type. 4
Scanner example import java. util. *; // so that I can use Scanner public class User. Input. Example { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("How old are you? "); int age = console. next. Int(); age 29 years 36 int years = 65 - age; System. out. println(years + " years to retirement!"); } } • Console (user input underlined): How old are you? 29 36 years until retirement! 5
Scanner example 2 import java. util. *; // so that I can use Scanner public class Scanner. Multiply { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Please type two numbers: "); int num 1 = console. next. Int(); int num 2 = console. next. Int(); int product = num 1 * num 2; 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. 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 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. next. Int(); Output: What is your age? Timmy java. util. Input. Mismatch. Exception at java. util. Scanner. next(Unknown Source) at java. util. Scanner. next. Int(Unknown Source). . . 7
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(); name = name. to. Upper. Case(); System. out. println(name + " has " + name. length() + " letters and starts with " + name. substring(0, 1)); Output: What is your name? Chamillionaire CHAMILLIONAIRE has 14 letters and starts with C • The next. Line method reads a line of input as a String. System. out. print("What is your address? "); String address = console. next. Line(); 8
Strings question • Write a program that outputs a person's "gangsta name. " – – – first initial Diddy last name (all caps) first name -izzle Example Output: Type your name, playa: Marge Simpson Your gangsta name is "M. Diddy SIMPSON Marge-izzle" 9
Strings answer // This program prints your "gangsta" name. import java. util. *; public class Gangsta. Name { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Type your name, playa: "); String name = console. next. Line(); // split name into first/last name and initials String first = name. substring(0, name. index. Of(" ")); String last = name. substring(name. index. Of(" ") + 1); last = last. to. Upper. Case(); String f. Initial = first. substring(0, 1); System. out. println("Your gangsta name is "" + f. Initial + ". Diddy " + last + " " + first + "-izzle""); } } 10
Formatting text with printf System. out. printf("format string", parameters); • A format string can contain placeholders to insert parameters: – %d integer – %f real number – %s string • these placeholders are used instead of + concatenation – Example: int x = 3; int y = -17; System. out. printf("x is %d and y is %d!n", x, y); // x is 3 and y is -17! • printf does not drop to the next line unless you write n 11
printf width – %Wd – %-Wd – %Wf –. . . integer, W characters wide, right-aligned integer, W characters wide, left-aligned real number, W characters wide, right-aligned for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 10; j++) { System. out. printf("%4 d", (i * j)); } System. out. println(); // to end the line } Output: 1 2 2 4 3 6 9 4 8 12 5 10 15 6 12 18 7 14 21 8 16 24 9 18 27 10 20 30 12
printf precision – %. Df real number, rounded to D digits after decimal – %W. Df real number, W chars wide, D digits after decimal – %-W. Df real number, W wide (left-align), D after decimal double gpa = 3. 253764; System. out. printf("your GPA is %. 1 fn", gpa); System. out. printf("more precisely: %8. 3 fn", gpa); Output: your GPA is 3. 3 more precisely: 3. 254 13
printf question • Modify our Receipt program to better format its output. – Display results in the format below, with $ and 2 digits after. • Example log of execution: How many people ate? 4 Person #1: How much did Person #2: How much did Person #3: How much did Person #4: How much did Subtotal: Tax: Tip: Total: your dinner cost? 20. 00 15 25. 0 10. 00 $70. 00 $5. 60 $10. 50 $86. 10 14
printf answer (partial). . . // Calculates total owed, assuming 8% tax and 15% tip public static void results(double subtotal) { double tax = subtotal *. 08; double tip = subtotal *. 15; double total = subtotal + tax + tip; // // System. out. println("Subtotal: System. out. println("Tax: $" + System. out. println("Tip: $" + System. out. println("Total: $" System. out. printf("Subtotal: System. out. printf("Tax: System. out. printf("Tip: System. out. printf("Total: $" + subtotal); tax); tip); + total); $%. 2 fn", subtotal); tax); tip); total); } } 15
- Slides: 15