Java Notes Prev: Java Example: Console: Hello Earthling | Next: Java Example: Console: Captitalize

Java Example: Console: Take me to your leader

This is similar to the previous program, but it also gets input from the user.

Console Input: Scanner

The java.util.Scanner class is a good way to read input from the console or a file. Even when you use a GUI user interface, Scanner will continue to be useful for reading data files.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
// File   : examples/introductory/console/FirstContact.java
// Purpose: Read text from console, write message back to console.
// Author : Fred Swartz = 2006-Dec-03 - Placed in public domain.

import java.util.*;                //Note 1

public class FirstContact {

    public static void main(String[] args) {
        //... Initialization
        String name;               // Declare a variable to hold the name.
        Scanner in = new Scanner(System.in);

        //... Prompt and read input.
        System.out.println("What's your name, Earthling?");
        name = in.nextLine();      // Read one line from the console.
        in.close();                //Note 2

        //... Display output
        System.out.println("Take me to your leader, " + name);
    }
}

Notes

  1. Altho we only need the Scanner class from the java.util package, the most common programming style is to make all classes (*) visible.
  2. Closing the console isn't really necessary, but it's a good habit. If we had been reading a file, which is common with Scanner, closing it would be important.
Line 11 - Declaring a local variable.
This tells the compiler to reserve some memory to hold a String. It's going to hold a name, so we called the variable (a place in the computer's memory) "name". The syntax for a simple declaration is to write the type of thing that a variable will hold (String in this case), followed by the variable name (name in this case).
Line 16 - Asking the user for a String.
in.nextLine() will read the next input line. It returns a string that can be stored into a variable.

This is an assignment statement. The part to the right of the "=" must produce a value, and this value is then stored in the variable on the left (name).

Line 20 - Putting two strings together (concatenation)
Concantenation, indicated by the plus sign (+), puts two strings together to build a bigger string, which is then passed as a parameter. The plus sign (+) is also used for addition of numbers.

Dialog version

See Dialog: Take me to your leader for how this program would be written using dialog input-output.