09 Ch03 3 Scanner
09 Ch03 3 Scanner
Interactive programs
We have written programs that print console output, but it is also possible to read input from the console.
The user types input into the console. We capture the input and use it in our program. Such a program is called an interactive program.
2
Copyright 2008 by Pearson Education
System.in
not intended to be used directly We use a second object, from a class Scanner, to help us.
3
Copyright 2008 by Pearson Education
Syntax:
// put this at the very top of your program import packageName.*;
Scanner methods
Method nextInt() nextDouble() next() nextLine() Description reads a token of user input as an int reads a token of user input as a double reads a token of user input as a String reads a line of user input as a String
6
Copyright 2008 by Pearson Education
Input tokens
token: A unit of user input, as read by the Scanner.
Tokens are separated by whitespace (spaces, tabs, newlines). How many tokens appear on the following line of input? 23 John Smith 42.0 "Hello world" $2.50 " 19"
Scanners as parameters
If many methods read input, declare a Scanner in main and pass it to the others as a parameter.
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; }
9
Copyright 2008 by Pearson Education
Cumulative sum
reading: 4.1 self-check: Ch. 4 #1-3 exercises: Ch. 4 #1-6
What if we want the sum from 1 - 1,000,000? Or the sum up to any maximum? We could write a method that accepts the max value as a parameter and prints the sum.
How can we generalize code like the above?
11
Copyright 2008 by Pearson Education
A failed attempt
An incorrect solution for summing 1-1000:
for (int i = 1; i <= 1000; i++) { int sum = 0; sum = sum + i; } // sum is undefined here System.out.println("The sum is " + sum);
sum's scope is in the for loop, so the code does not compile.
cumulative sum: A variable that keeps a sum in progress and is updated repeatedly until summing is finished.
The sum in the above code is an attempt at a cumulative sum.
12
Copyright 2008 by Pearson Education
Key idea: Cumulative sum variables must be declared outside the loops that update them, so that they will exist after the loop.
13
Copyright 2008 by Pearson Education
Cumulative product
This cumulative idea can be used with other operators:
int product = 1; for (int i = 1; i <= 20; i++) { product = product * 2; } System.out.println("2 ^ 20 = " + product);
14
Copyright 2008 by Pearson Education
15
Copyright 2008 by Pearson Education
18
Copyright 2008 by Pearson Education
20
Copyright 2008 by Pearson Education
21