80 likes | 235 Views
Building Java Programs Chapter 3. The scanner class and user input. Let’s G et 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.
E N D
Building Java ProgramsChapter 3 The scanner class and user input
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.
Scanner For most objects (including Scanner objects), we create a new instance with the new keyword: TypeNamemyInstance = new TypeName(any, parameters); For a Scanner, it looks like this: Scanner scanner = newScanner(System.in);
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: importjava.util.*; Eclipse will offer to do this for us if we mouse over the word “Scanner” when it has a red squiggly.
Scanner We finally have enough to start using the methods on our Scanner object: importjava.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); } }
Scanner importjava.util.*; public classMyInteractiveProgram { public static voidmain(String[]args) { Scanner scanner = newScanner(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!
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
In your notebook The following method signatures are missing their class. List the class to which each method belongs. doubleabs(double); doublenextDouble(); char charAt(int); intceil(double); intlength(); String substring(int, int);