• Understand Java Scanner
  • Understand the differences between Scanner and String.
  • Understand the details of declaring variables, allocating objects, and using objects of type Scanner.
  • Understand how to call Scanner instance methods
  • Java Scanner

    We have already used a Scanner to read input from the terminal window. In our early programs we mimicked sample code. At this point we can understand what is happening in terms of defining a reference variable, assigning the variable to an object, and using instance methods of the object. The Programming Pattern 3 is repeated here with line numbers for discussion.

    Line 1 imports the Scanner class so that we can use it to declare variables of type Scanner. The Scanner class is in the java.util package. In Java a package collects classes together for easy access. We study the details of packages in Packages, ADTs.

    Line 5 accomplishes the following.

    • declares a variable in, of type Scanner
    • creates a Scanner object using the new operator
    • connects the Scanner object to System.in, the terminal window. We will learn to connect a Scanner to a file.
    • assigns the Scanner object to the variable in
    • After line 5, the variable in references a Scanner object.

    Line 7 calls a the method nextLine, which is an instance method of a Scanner object. nextLine reads the next line from the terminal window as a String, which is assigned to the String variables name.

    Lines 10 and 12 call the method nextDouble, which is an instance method of a Scanner object. nextDouble scans the input stream for a double. You can type a bunch of white space (spaces, tabs, enter) before you enter a double. If the next data types in the terminal window is not a double, you will generate a Java exception (java.util.InputMismatchException). We study Java exceptions in XXX.

    Tags: object class