Skip to main content
ICT
Lesson A7 - Simple I/O
 
Main   Previous Next
 

A. Reading Input with the Scanner Class page 3 of 7

  1. Some of the programs from the preceding lessons have been written without any flexibility. To change any of the data values in the programs, it is necessary to change the variable initializations, recompile the program, and run it again. Sometimes prompting the user for a value and then processing the data is more efficient and convenient.

  2. However, accepting user input in Java can be complex. Throughout this curriculum, we will use the Scanner class to make processing input easier and less tedious.

  3. Just as the System class provides System.out for output, there is an object for input, System.in. Unfortunately, Java’s System.in object does not directly support convenient methods for reading numbers and strings. We need to have a class sitting between the System.in object and ourselves to filter what comes through. This is what the Scanner class does.

  4. Scanner is part of the java.util package, so we need to start off by adding the Scanner class to our import section.

    import java.util.Scanner;

  5. Next, we create our Scanner object and pass in the System.in object.

    Scanner in = new Scanner(System.in);

    This tells the Scanner to look at the System.in object for all of its input. In Student Lesson A13, we will learn how to change the object we pass to the Scanner so that we can read the data stored in text files.

  6. Here are some example statements:

    When the statement num1 = in.nextInt() is encountered, the program pauses until an appropriate value is entered on the keyboard.

  7. Any whitespace (spaces, tabs, newline) will separate input values. When reading values, whitespace keystrokes are ignored.

  8. When requesting data from the user via the keyboard, it is good programming practice to provide a prompt. An unintroduced input statement leaves the user hanging without a clue of what the program wants. For example:

    System.out.print("Enter an integer --> ");
    number = in.nextInt();

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.