building java programs chapter 3

7
1 BUILDING JAVA PROGRAMS CHAPTER 3 THE SCANNER CLASS AND USER INPUT

Upload: thad

Post on 04-Jan-2016

27 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Building Java Programs Chapter 3

1

BUILDING JAVA PROGRAMSCHAPTER 3THE SCANNER CLASS AND USER INPUT

Page 2: Building Java Programs Chapter 3

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.

Page 3: Building Java Programs Chapter 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);

Page 4: Building Java Programs Chapter 3

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.

Page 5: Building Java Programs Chapter 3

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); }}

Page 6: Building Java Programs Chapter 3

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); }}

Page 7: Building Java Programs Chapter 3

7

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? 3A circle with radius 3.0 has circumference 18.8495559215A circle with radius 3.0 has area 28.27433388230A sphere with radius 3.0 has volume 113.0973355292