Scanner Class

click here for complete presentation

What is the Scanner Class?

The Scanner class allows a program to read in data from the keyboard

To use a the Scanner, follow these steps

1. Import the Scanner
import java.util.Scanner;
2. Make a new instance of the Scanner
Scanner myScanObj = new Scanner(System.in);
3. Use one of the following methods to read in input
nextInt(); - Scans an integer value
nextDouble() Scans a double value
nextLine() Scans more than one word
next(); - Scans only one word

Example

import java.util.Scanner;

public class ScannerExample
{

public static void main (String [] args)
{

Scanner myScanObj = new Scanner(System.in);

System.out.println("Enter a sentence:");
String sentence = myScanObj.nextLine();

System.out.println("Enter an integer:");
int num1 = myScanObj.nextInt();

System.out.println("Enter a double:");
double num2 = myScanObj.nextDouble();

System.out.println("Your sentence:\n" + sentence);
System.out.println("Your Number Integer:\n" + num);
System.out.println("Your Number Integer:\t" + num);

}
}

Scanner Class