Skip to main content
Engineering LibreTexts

2.5: From the Java Library- java.util.Scanner

  • Page ID
    15067
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    If we wish to write useful interactive programs, we must be able to receive information from the user as well as send information to him or her. We saw, in the previous chapter, that output from a program can be sent to the console window by simply using the System.out.print() and System.out.println() statements. In this section we describe two simple ways that Java can handle keyboard input. Receiving input from the keyboard, together with sending output to the console window, creates one of the standard user interfaces for programs.

    Recall, that in Java, any source or destination for I/O is considered a stream of bytes or characters. To perform keyboard input, we will extract characters from System.in, the input stream connected to the keyboard. Getting keyboard input from System.in involves two complications that are not present in dealing with System.out.println(). First, normal keyboard input data requested of a user consists of a sequence of characters or digits which represent a word, phrase, integer, or real number. Normally, an entire sequence of characters typed by the user will represent data to be stored in a single variable with the user hitting the return or enter key to signal the end of a piece of requested data. Java has a special class, BufferedReader, that uses an input stream and has a method that collects characters until it reads the character or characters that correspond to hitting the return or enter key. A second complication for reading input involves the problem of how to handle receiving data that is not in the same format as expected. The BufferedReaderclass handles this problem by using certain exceptions, a special kind of error message, that must be handled by the programmer. Chapter 11 is devoted to exceptions and we will avoid their use, as far as possible, until that time.

    There is an alternate way to handle keyboard input in the Java 2 Platform Standard Edition 5.0 (Java SE 5.0). A Scannerclass has been added to the java.util package which permits keyboard input without forcing the programmer to handle exceptions. We introduce the Scanner class in the next subsection and then describe how a user defined class introduced in Chapter 4 can function in an equivalent fashion to permit simple keyboard input.

    Keyboard Input with the Scanner Class

    A partial definition of Scanner is shown in Figure 2.25. Note that the Scanner methods listed are but a small subset of the public methods of this class. The Scanner class is in the java.util package so classes that use it should import it with the following statement:

    import java.util.Scanner;

    The Scanner class is designed to be a very flexible way to recognize chunks of data that fit specified patterns from any input stream. To use the Scanner class for keyboard input, we must create a Scanner instance and associate it with System.in. The class has a constructor for this purpose, so the statement

    Scanner sc = new Scanner(System.in);

    declares and instantiates an object that can be used for keyboard input. After we create a Scanner object, we can make a call to nextInt(), nextDouble(), or next() to read, respectively, an integer, real number, or string from the keyboard. The program in Figure [fig-scannerprog] demonstrates how an integer would be read and used. When the nextInt()

    import java.util.Scanner;
    
    public class TestScanner 
    {
      public static void main(String[] args) 
      {               // Create Scanner object
        Scanner sc = new Scanner(System.in); 
        System.out.print("Input an integer:"); // Prompt
        int num = sc.nextInt();         // Read an integer
        System.out.println(num + " squared = " + num*num);
      } //main()
    } // TestScanner class

    method is executed, no further statements are executed until an int value is returned by the method. Normally this does not happen until the user has typed in the digits of an integer and hit the return or enter key. Thus executing the main()method of the TestScanner class will result in the output

    Input an integer:

    to the console window and the program will wait for the user to type in an integer and hit the return or enter key. After this has been done the output will look something like:

    Input an integer:123
    123 squared = 15129

    Keyboard input of real numbers and strings are handled in a similar manner.

    Keyboard input will allow us to create examples of command line interfaces for interactive programs. For example, the code

    Scanner sc = new Scanner(System.in); 
    Riddle riddle = new Riddle(
      "What is black and white and red all over?",
      "An embarrassed zebra.");
    System.out.println("Here is a riddle:");
    System.out.println(riddle.getQuestion());
    System.out.print("To see the answer, ");  // Prompt
    System.out.println("type a letter and enter.");
    String str = sc.next();         // Wait for input
    System.out.println(riddle.getAnswer());

    will display a riddle question and prompt the user to type a letter and to hit the enter key to see the answer. In the next chapter, we will develop new methods for the OneRowNim class that will be able to use int values input from the keyboard for the next move.

    We must mention that, since the Scanner class is designed as a flexible tool for recognizing chunks of data from any input stream, it has some properties that may be unexpected and not totally compatible with simple keyboard input. A Scanner object has a set of character strings that separate or delimit the chunks of data that it is looking for. By default, this set of delimiters consists of any non-empty sequence of white space characters, that is, the space, tab, return, and newline characters. This will allow a user to input several integers separated by spaces before hitting the enter key. This might be handled by code like:

    System.out.print("Input two integers and an enter:");  
    int num1 = sc.nextInt();
    int num2 = sc.nextInt();

    White space as delimiters also means that the next() method cannot return an empty string nor can it return a string that contains any spaces. For example, consider the code:

    System.out.print("Input the first president of the USA:");  
    String str = sc.next();

    If one types "George Washington" and hits the enter key, the string str will store only "George". In order to get a Scanner object to read strings that contain spaces, we must use the useDelimiter() method to define the set of delimiters as just that character string generated by hitting the enter key. For example, for some Windows operating systems, the statement

    sc = sc.useDelimiter("\r\n"); 

    will result in the next() method returning the entire string of characters input from the keyboard up to but not including those generated by hitting the enter key.

    You should also be aware that just because we can use a Scanner object to write Java code that ignores exceptions does not mean that exceptions will not be generated by keyboard input. If the user enters letters rather than digits for the nextInt() method to process, the program will be terminated with an error message.

    It must be stressed that the strategy for handling keyboard input outlined above is a temporary strategy until the topic of exceptions is covered in Chapter 11. Real software applications that use keyboard input should carefully handle the possibility that a user will enter something unexpected. In Java, this can only be done by handling exceptions.

    Keyboard Input with the KeyboardReader Class

    If you are using an older version of Java that does not have the Scanner class, a user-defined class can be used instead. A KeyboardReader class that uses the BufferedReader class will be developed in Chapter 4. It has methods that read data from the keyboard in a manner very similar to those of the Scanner class. A partial list of its public methods is given in the UML class diagram shown in Figure 2.27. To use the KeyboardReader class for keyboard input, copy the source code KeyboardReader.java from Chapter 4 into the same directory as the source code of your current Java class (and add it to your current project if you are using a integrated development environment).

    To use a KeyboardReader object, we need to create an instance of the class with a constructor. Then calling one of the three methods will return an int, double, or String when data is input from the keyboard. Any of the three methods of a KeyboardReader object will attempt to process the entire string input from the keyboard up to the point that the enter key is hit. That is, the character or characters generated by hitting the return or enter key is the delimiter used by KeyboardReader. The TestKeyboardReader class definition in Figure [fig-kbreaderprog]

    public class TestKeyboardReader 
    {
      public static void main(String[] args) 
      {             // Create KeyboardReader object
        KeyboardReader kb = new KeyboardReader(); 
        System.out.print("Input an integer:"); // Prompt
        int num = kb.getKeyboardInteger(); // Read an integer
        System.out.println(num + " squared = " + num*num);
      } //main()
    } // TestKeyboardReader class

    reads an integer from the keyboard and squares it just like the TestScanner class. In the remainder of the text, any time the Scanner class is used for keyboard input, the same program can be run using the KeyboardReader class after making the obvious substitutions.

    Modify the main() method of the TestScanner class so that it reads a real number from the keyboard rather than an integer.

    access modifier

    class-level variable

    default value

    delimiter

    empty string

    flow of control

    interface

    local variable

    method call and return

    null pointer

    null pointer exception

    pointer

    reference

    reference variable

    static modifier

    user interface

    Dot notation is used to refer to an object’s public elements.

    Designing a class is a matter of deciding what role it will play and what information and actions it will have.

    Writing a Java program is a matter of defining one or more classes. A class definition serves as a template for creating instance of the class.

    Classes typically contain two kinds of elements, variables and methods. An object’s state is defined by its instance variables.

    Class elements that are declared public can be accessed by other objects. Elements that are declared private are hidden from other objects.

    A class’s instance variables are usually declared private so they cannot be accessed directly by other objects.

    An object’s public instance methods can be called by other objects. Thus, they make up the object’s interface with other objects.

    Object instantiation is the process of creating an object, using the new operator in conjunction with a constructor method.

    A class definition consists of a header and a body. The header gives the class a name, specifies its accessibility ( public), and its place in the Java class hierarchy (extends Object). The class body contains declarations of the class’s variables and definitions of its methods.

    By default, a newly defined class is consider a subclass of Object.

    Class elements that are declared static, such as the main() method, are associated with the class (not with its instances).

    A Java application program must contain a main() method, which is where it begins execution.

    Methods that are used solely for the internal operations of the class should be declared private.

    An instance variable declaration reserves memory for the instance variable within the object, associates a name and a type with the location, and specifies its accessibility.

    A method definition consists of two parts: a header, which names the method and provides other general information about it, and a body, which contains its executable statements.

    Declaring a variable creates a name for an object but does not create the object itself. An object is created by using the new operator and a constructor method.

    The Java code fragment prints out the following:

    The singing king.

    For the Riddle class (Fig. [fig-riddleclass2]),

    The name of the class: Riddle

    The names of two instance variables: question, answer

    The names of three methods: Riddle(), getQuestion(), getAnswer()

    For RiddleUser class (Fig. [fig-riddleuser]),

    The names of two Riddle instances: riddle1, riddle2

    All six method calls of the Riddle objects in the program:

    Riddle("What is black and white and red all over?", 
                                "An embarrassed zebra.")
    Riddle("What is black and white and read all over?", 
                                         "A newspaper.")
    riddle1.getQuestion()
    riddle1.getAnswer()
    riddle2.getQuestion()
    riddle2.getAnswer()

    Qualified names: riddle1.getQuestion() and riddle1.getAnswer()

    Definition of new instance variable in the Riddle class:

    private String hint = "This riddle is to easy for a hint";

    The header for a getHint() method of the Riddle class, which should be a public method, is:

    public String getHint();

    The header for a setHint() method of the Riddle class is:

      public void setHint(String aHint);

    The result type is void. Although the identifier used for the parameter is arbitrary, it is a good practice to make it descriptive, by referring in some way to the hint instance variable.

    The partial definition of the Student class is given below.

    public class Student
    {  private String firstName;
       private String lastName;
       private int studentID;
    
       public void setStudent(String fName, String lName, 
                                                  int anID);
       public int getStudentID();
       public String getStudentName();
    }

    A main method that reads and squares a real number is given below.

    public static void main(String[] args) 
    {               // Create Scanner object
      Scanner sc = Scanner.create(System.in); 
      System.out.print("Input a real number:");    // Prompt
      double realNum= sc.nextDouble();      // Read a double
      System.out.println(num + " squared = " + realNum*realNum);
    } //main()

    Consider the transaction of asking your professor for your grade in your computer science course. Identify the objects in this transaction and the types of messages that would be passed among them.

    Now suppose the professor in the previous exercise decides to automate the transaction of looking up a student’s grade and has asked you to design a program to perform this task. The program should let a student type in his or her name and ID number and the program then should display his or her grades for the semester, with a final average. Suppose there are five quiz grades, three exams, and two programming exercise grades. Identify the objects in this program and the type of messages that would be passed among them. (Hint: The grades themselves are just data values, not objects.)

    In the RiddleUser class (Fig. [fig-riddleuser]), give two examples of object instantiation and explain what is being done.

    Explain the difference between a method definition and a method call. Give an example of each from the Riddle and RiddleUser examples discussed in this chapter.

    In the RiddleUser class (Fig. [fig-riddleuser]), identify three examples of method calls and explain what is being done.

    Describe how the slogan “define, create, manipulate” applies to the Riddle example.

    An identifier is the name for a


     ,


     , or a


     .

    Which of the following would be valid identifiers?

    int  74ElmStreet  Big_N     L$&%#   boolean  Boolean  _number
    Int  public       Private   Joe     j1       2*K      big numb

    Explain the difference between a class variable and an instance variable.

    Identify the syntax error (if any) in each declaration. Remember that some parts of an instance variable declaration are optional.

    public boolean isEven ;

    Private boolean isEven ;

    private boolean isOdd

    public boolean is Odd ;

    string S ;

    public String boolean ;

    private boolean even = 0;

    private String s = helloWorld ;

    Write declarations for each of the following instance variables.

    A private boolean variable named bool that has an initial value of true.

    A public String variable named str that has an initial value of "hello".

    A private int variable named nEmployees that is not assigned an initial value.

    Identify the syntax error (if any) in each method header:

    public String boolean()

    private void String ()

    private void myMethod

    private myMethod()

    public static void Main (String argv[])

    Identify the syntax error (if any) in each assignment statement. Assume that the following variables have been declared:

    public int m;
    public boolean b;
    public String s;

    2

    m = "86" ;

    m = 86 ;

    m = true ;

    s = 1295 ;

    s = "1295" ;

    b = "true" ;

    b = false

    Given the following definition of the NumberAdder class, add statements to its main() method to create two instances of this class, named adder1 and adder2. Then add statements to set adder1’s numbers to 10 and 15, and adder2’s numbers to 100 and 200. Then add statements to print their respective sums.

    public class NumberAdder
    {
        private int num1;
        private int num2;
    
        public void setNums(int n1, int n2)
        {
          num1 = n1;
          num2 = n2;
        }
        public int getSum()
        {
          return num1 + num2 ;
        }
    
        public static void main(String args[])
        {
        }
    }

    For the NumberAdder class in the previous exercise, what are the names of its instance variables and instance methods? Identify three expressions that occur in the program and explain what they do. Identify two assignment statements and explain what they do.

    Explain the difference between each of the following pairs of concepts.

    A method definition and a method call.

    Declaring a variable of reference type and creating an instance.

    A variable of reference type and a variable of primitive type.

    Define a Java class named NumberCruncher that has a single int variable as its only instance variable. Then define methods that perform the following operations on its number: get, double, triple, square, and cube. Set the initial value of the number with a constructor as was done with the instance variables in the Riddle class.

    Write a main() method and add it to the NumberCruncher class defined in the previous problem. Use it to create a NumberCruncher instance, with a certain initial value, and then get it to report its double, triple, square, and cube.

    Write a Java class definition for a Cube object, that has an integer attribute for the length of its side. The object should be capable of reporting its surface area and volume. The surface area of a cube is six times the area of any side. The volume is calculated by cubing the side.

    Write a Java class definition for a CubeUser object that will use the Cube object defined in the previous exercise. This class should create three Cube instances, each with a different side, and then report their respective surface areas and volumes.

    Challenge: Modify your solution to the previous exercise so that it lets the user input the side of the cube. Follow the example shown in this chapter’s “From the Java Library” section.

    Challenge: Define a Java class that represents an address book entry, Entry, which consists of a name, address, and phone number, all represented as Strings. For the class’s interface, define methods to set and get the values of each of its instance variables. Thus, for the name variable, it should have a setName() and a getName() method.

    Draw a UML class diagram to represent the following class hierarchy: There are two types of languages, natural languages and programming languages. The natural languages include Chinese, English, French, and German. The programming languages include Java, Smalltalk and C++, which are object-oriented languages, FORTRAN, COBOL, Pascal, and C, which are imperative languages, Lisp and ML, which are functional languages, and Prolog, which is a logic language.

    Draw a UML class diagram to represent different kinds of automobiles, including trucks, sedans, wagons, SUVs, and the names and manufacturers of some popular models in each category.

    Draw a UML object diagram of a triangle with attributes for three sides, containing the values 3, 4, and 5.

    Suppose you are writing a Java program to implement an electronic address book. Your design is to have two classes, one to represent the user interface and one to represent the address book. Draw a UML diagram to depict this relationship. See Figure [fig-p63f2].

    Draw an UML object diagram to depict the relationship between an applet, which serves as a user interface, and three Triangles, named t1, t2, and t3.


    This page titled 2.5: From the Java Library- java.util.Scanner is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.