Sample Code
import java.util.Scanner; //could also have used import java.util.*;
public class ScannerClass
{
public static void main(String[] args) //must have this method or you will be severely criticized by ye olde compiler (JVM actually)
{
//create an object of the Scanner class so you can use the methods contained in it through //use of the dot operator
Scanner in = new Scanner(System.in);
int num1;
double bigNum;
System.out.println("Please enter an integer");
num1 = in.nextInt(); //nextInt() is a method of the Scanner class
System.out.println ("Please enter a double");
bigNum = in.nextDouble(); //nextDouble() is a method of the Scanner class
System.out.println("The integer you entered: " + num1); //+ is the concatenation operator in Java, note the space
System.out.println ("The double you entered: " + bigNum);
}
}
Output
Please enter an integer
10
Please enter a double
10.5
The integer you entered: 10
The double you entered: 10.5
Note
The Scanner class incorporates a safety feature of Java that we will cover in more detail later - exception handling
If you enter an incorrect data type the program will "throw an exception"