Download presentation
Presentation is loading. Please wait.
Published byLester Chambers Modified over 9 years ago
1
1 BUILDING JAVA PROGRAMS CHAPTER 3 THE SCANNER CLASS AND USER INPUT
2
2 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.
3
3 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);
4
4 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.
5
5 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); }
6
6 SCANNER What will this output? I don’t know! It depends on what you type at runtime! 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); }
7
7 LET’S TRY IT! 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
8
8 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);
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.