Scanner class is predefined and built into Java for your use. It’s used to read user input in a Java program.
For this exercise, we will build a program that walks us through writing code that uses the
Scanner class together. Before we can code our own class, we must import the Scanner class, which you can do using the following:
Let’s begin by declaring the
Scanner class as a variable that we will call
Scanner input = new Scanner(System.in);
Notice how we have placed
System.in within the brackets in our declaration. This is what will allow our program to read user input from the console. The
Scanner class can also read input from a file; we will cover that in the next exercise.
Next, let’s take a look at the code that is required to read user input. The
Scanner class can read different types of values that can be saved into different variable types. The list below outlines some (but not all) the different variable types and the code required to read the variables into the program:
Scanner class has many functions, including the ability to validate and convert variables.
Some examples include:
||This function returns a boolean that validates if there is another line in the input of the defined scanner.|
||This function returns a boolean that validates if there is another int in the input of the defined scanner.|
||This function helps us specify what delimiters we want to use. A delimiter is used to separate data units. Delimiters can be especially useful when a program is required to read csv files.|
||This function can be used to convert different variable types to string variables. In this example, we are converting an int to a string.|
Scanner class at the top of your program, then declare the
Scanner in the
Now we can begin interacting with the program!
Write the print statement that asks the user what their name is. Then use
.next() to save their answer to the variable
System.out.printf() to print the following statement:
Hello "userName"! It's nice to meet you.
where “userName” is replaced with the input provided by the user.
Now let’s test it out! First, compile your program using the correct command in the terminal.
Now, run your program using the correct command in the terminal.