Java User Input
We have seen how using the print(), println() and printf() methods can provide programs with the ability to output information to an output console. This is really useful for user messages or observing the results of computations, etc. In this lesson you will learn how to facilitate data input via the output console using the Scanner class.
The Scanner class is part of the java.util package and must be imported before it us used. As usual, this is an import statement located directly after the package statement:
package inputapplication; import java.util.Scanner; // Import the Scanner class public class InputApplication { public static void main(String[] args) { } }
To use the Scanner class, you must create a scanner object using the following (change objectName to your choice):
Scanner objectName =new Scanner(System.in);
Then, all available scanner methods will be available to your program. Click here for a full list of Scanner methods. Scanner methods facilitate the reading and processing of data. This data, like all other data in Java, will have a datatype and it is important that the appropriate Scanner method is used to avoid runtime errors that could crash your program.
Let’s see how this works in practice. The following program will request the user input their first name (a string) which will be concatenated with a message welcoming them to this program. The nextLine() method is used to read strings, but before we can use that we need to create a Scanner object
package inputapplication; import java.util.Scanner; // Import the Scanner class public class InputApplication { public static void main(String[] args) { // Create a new Scanner object Scanner myObj = new Scanner(System.in); //Output a message to the user System.out.println("Please enter your first name"); // Read the user input String firstName = myObj.nextLine(); // Output the user input System.out.println("Welcome " + firstName + "!"); } }
The output should be:
run:
Please enter your first name
Andrew
Welcome Andrew!
BUILD SUCCESSFUL (total time: 9 seconds)
Scanner Methods
You have seen how to read and process a string using the nextLine() method. Java can read and process a number of other datatypes, these include:
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
nextBigInteger() Reads a BigInteger value from the user
nextBigDecimal() Reads a BigDecimal value from the user
We can use multiple scanner methods in the same input operation. For example, imagine a school application that needs a string student name, an int student number and a double student grade. Once we create the scanner object we can use it as many times as we want, and in this case we need to use it three time to input three pieces of data with different datatypes. Let see how that might be coded:
public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Please enter student name, number and grade:"); //String input String fName = myObj.nextLine(); //int and double inputs int studentId = myObj.nextInt(); double studentGrade = myObj.nextDouble(); //Outputs System.out.println("Student Name: " + fName); System.out.println(fName + "'s ID: " + studentId); System.out.println(fName + "'s grade: " + studentGrade + "%"); }
The output should be:
run:
Please enter student name, number and grade:
Andrew Tully
2004453
95
Student Name: Andrew Tully
Andrew Tully’s ID: 2004453
Andrew Tully’s grade: 95.0%
BUILD SUCCESSFUL (total time: 78 minutes 10 seconds)
Getting the correct order of inputs, and entering the correct type of data, is critical. If the wrong input is entered, say text in a numerical input, an InputMismatchException exception will result. It would be wise to implement a try-catch block to prevent your program from crashing, click here read more about exception handling.