Chapter 3d Scanner - Everett School District
Download
Report
Transcript Chapter 3d Scanner - Everett School District
BUILDING JAVA
PROGRAMS
CHAPTER 3
THE SCANNER CLASS AND USER INPUT
1
LET’S GET INTERACTIVE!
We’ve been limited to writing programs that are
completely self-contained… everything they do is based on
information you provided when writing the program.
It’s time to learn how to make our programs interactive, so
they can ask for input at runtime!
We’ll do this using an instance of the Scanner class.
2
SCANNER
For most objects (including Scanner objects), we create a
new instance with the new keyword:
TypeName myInstance = new TypeName(any,
parameters);
For a Scanner, it looks like this:
Scanner scanner = new Scanner(System.in);
3
A BIT MORE MAGIC: IMPORT
There’s one other thing we have to do before we can start
using our Scanner. We have to tell Java where it can find
it!
We do this with one more magic Java keyword, import, at
the top of the Java source code file:
import java.util.*;
Eclipse will offer to do this for us if we mouse over the word
“Scanner” when it has a red squiggly.
4
SCANNER
We finally have enough to start using the methods on our Scanner object:
import java.util.*;
public class MyInteractiveProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Type something: ");
String word = scanner.next();
System.out.print("The first word was: " + word);
}
}
5
SCANNER
import java.util.*;
public class MyInteractiveProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Type something: ");
String word = scanner.next();
System.out.print("The first word was: " + word);
}
}
What will this output?
I don’t know! It depends on what you type at runtime!
6
LET’S TRY IT!
Start Eclipse and create a “GeometryHelper” project and class. Use
Scanner’s nextDouble() method to ask for a radius, and then print the
circumference, area, and volume for a circle and sphere with that radius:
What is the radius? 3
A circle with radius 3.0 has circumference 18.8495559215
A circle with radius 3.0 has area 28.27433388230
A sphere with radius 3.0 has volume 113.0973355292
𝐶𝑖𝑟𝑐𝑢𝑚𝑓𝑒𝑟𝑒𝑛𝑐𝑒 = 2𝜋𝑟
𝐴𝑟𝑒𝑎 = 𝜋𝑟 2
𝑉𝑜𝑙𝑢𝑚𝑒 =
4 3
𝜋𝑟
3
7
IN YOUR NOTEBOOK
The following method signatures are missing their class. List the class to
which each method belongs.
double abs(double);
double nextDouble();
char charAt(int);
int ceil(double);
int length();
String substring(int, int);
8