Scanner

So far we have only defined variables in our code, so whenever we run the programme we get the same output. It would be useful to be able to get data input from a user and do something with it.

Java provides a utility called Scanner which we can get typed user input and convert it into a String. To use the scanner we need to tell it where to look for this input - in this case we will use the System input: System.in

The whole line to create a scanner, and configure it to look for input from the system could appear as follows:

java.util.Scanner inputScanner = new java.util.Scanner(System.in);
This is a rather lengthy piece of code, in part because the scanner belongs in a package (a group of related code) named java.util. It would be nicer if we could just refer to it using Scanner, and we can - we simply import the package using a line of code at the top of the file as follows:
import java.util.Scanner;
and from that point on we can use the simpler code:
Scanner inputScanner = new Scanner(System.in);

The scanner can read different types of data (not just strings of text, but also various types of numbers). If we want to read a line of text into the system, then we can write code as follows:

String userInput = inputScanner.nextLine();

Create a new command line project (using the steps in the new project tutorial if necessary), to read a line of data in from the user, example code for this is shown below:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        //create a scanner
        Scanner inputScanner = new Scanner(System.in);
        //read a line text entered by the user, store it in a variable called userInput
        String userInput = inputScanner.nextLine();
    }
}

Run the programme, and you should see that in the output window, instead of the usual Process finished message, there is just one line - this is because the scanner is waiting for a line type typed, so the program is paused. It will look similar to this output window mid process

Click inside the output window and type the word 'test', then press enter. You should see that the programme ends

Task

So far the programme is not particularly helpful, or user friendly.

  1. Add a line of code, before the line that gets the user input, which will display a message to the user asking them to type their name
  2. Test that you message appears and the programme runs and behaves as expected
  3. Modify the programme so it outputs "Hello " followed by the user's name.
  4. Test the programme