Source of ScannerDemo.java


  1: //ScannerDemo.java
  2: //Illustrates the creation and use of a Scanner object for keyboard input.
  3: 
  4: import java.util.Scanner;
  5: 
  6: public class ScannerDemo
  7: {
  8:     public static void main(String[] args)
  9:     {
 10:         Scanner scannerObject = new Scanner(System.in);
 11: 
 12:         System.out.println("Enter two whole numbers");
 13:         System.out.println("separated by one or more spaces:");
 14: 
 15:         int n1, n2;
 16:         n1 = scannerObject.nextInt();
 17:         n2 = scannerObject.nextInt();
 18:         System.out.println("You entered " + n1 + " and " + n2);
 19: 
 20:         System.out.println("Next enter two numbers.");
 21:         System.out.println("A decimal point is OK.");
 22: 
 23:         double d1, d2;
 24:         d1 = scannerObject.nextDouble();
 25:         d2 = scannerObject.nextDouble();
 26:         System.out.println("You entered " + d1 + " and " + d2);
 27: 
 28:         System.out.println("Next enter two words:");
 29: 
 30:         String s1, s2;
 31:         s1 = scannerObject.next();
 32:         s2 = scannerObject.next();
 33:         System.out.println("You entered \"" + s1 + "\" and \"" + s2 + "\"");
 34: 
 35:         s1 = scannerObject.nextLine(); //To get rid of '\n'
 36: 
 37:         System.out.println("Next enter a line of text:");
 38:         s1 = scannerObject.nextLine();
 39:         System.out.println("You entered: \"" + s1 + "\"");
 40:     }
 41: }