Read user input using the Scanner class
-
Last Updated: November 27, 2023
-
By: javahandson
-
Series
In this article, we will learn what is a Scanner class and how to read user input using the Scanner class with proper examples. If you want to learn more about other Java, Java 8, or Spring concepts then please check the above menu options.
Scanner is a predefined class that is part of java.util package. Scanner class helps us to read the inputs from the keyboard as well as text files. The Scanner class splits the text into multiple tokens separated by default delimiter i.e. space.
Tokens can be stored in variables. Tokens can be of different data types such as integer, String, float, etc.
The Scanner class provides a set of methods that helps us to read the primitive data types in a simple way. We will learn more about these different methods in one of the below sections. But before that, we will learn about Scanner class constructors.
In this section, we will learn about a few important Scanner class constructors that will help us to create Scanner class objects.
We have learned about the Input stream and Output stream in one of our previous articles accessing data from the keyboard. If you have enough time then I recommend you to go through that article once. The important point that you should know is that System.in is an input stream object and it represents a standard input device i.e. keyboard.
When we are creating the Scanner class object we have to pass the System.in as an argument to its constructor. So that the Scanner object understands it has to take the input from the keyboard.
InputStream inputStream = System.in; Scanner scanner = new Scanner(inputStream);
This constructor helps to read the data from the input file. Here we have to pass the File class object as an argument to the Scanner class constructor. File class is present in the java.io package.
File file = new File("MyFile.txt"); Scanner scanner = new Scanner(file);
This constructor helps to read the data from the input file or some input source such as URI. Here we have to pass the Path class object as an argument to the Scanner class constructor. Path class is present in java.nio package.
// Read from file File file = new File("MyFile.txt"); Path path = file.toPath(); Scanner scanner = new Scanner(path);
Java Path class is an advanced version of the File class. If you want to get more information on Path Vs File then please check this article https://www.javatpoint.com/java-path-vs-file
The above variants of constructors also come with charset as an argument:
Here the charsetName will let us know the input will be in which format or we should expect the text in which format. Ex. UTF-8, UTF-16BE, UTF-32BE, UTF-16LE, and UTF-32LE.
In this section, we will learn about a few important Scanner class methods that will help us retrieve the tokens from the Scanner object.
This method returns true if the next token is available in the input String or statement.
It reads the next token from the statement in the String format or we can say it is used to read the String value.
This method returns true if there is another line in the input of this scanner.
It is used to read the input String till the end of the line.
This method returns true if the next token available in the input statement can be interpreted as an integer value using the nextInt() method.
It reads the next token in the integer format or we can say it is used to read integer values.
This method returns true if the next token available in the input statement can be interpreted as a float value using the nextFloat() method.
It reads the next token in the float format or we can say it is used to read float value.
This method skips the token that is specified in the argument of this method.
The above are the few most important constructors and methods that will be widely used while developing applications. There are a few more constructors and methods but they are rarely or never used. If you want to get information on those then you can refer to the Oracle documentation.
In the below section, we will see a few examples to understand the above concepts better.
package com.java.handson.io; import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String name = null; int age = 0; float marks = 0.0f; System.out.print("Enter name, age and marks for a student : "); if (scanner.hasNext()) { name = scanner.next(); } if (scanner.hasNextInt()) { age = scanner.nextInt(); } if (scanner.hasNextFloat()) { marks = scanner.nextFloat(); } System.out.println("Name of the student is : "+name); System.out.println("Age of the student is : "+age); System.out.println("Marks of the student is : "+marks); } } Output: Enter name, age and marks for a student : John 14 450.50 Name of the student is : John Age of the student is : 14 Marks of the student is : 450.5
package com.java.handson.io; import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String name = null; int age = 0; float marks = 0.0f; System.out.print("Enter name, age and marks for a student : "); scanner = scanner.skip("Eliza"); if (scanner.hasNext()) { name = scanner.next(); } if (scanner.hasNextInt()) { age = scanner.nextInt(); } if (scanner.hasNextFloat()) { marks = scanner.nextFloat(); } System.out.println("Name of the student is : "+name); System.out.println("Age of the student is : "+age); System.out.println("Marks of the student is : "+marks); } } Output: Enter name, age and marks for a student : Elizabeth 14 405.50 Name of the student is : beth Age of the student is : 14 Marks of the student is : 405.5
In the above example, we have given the input name Elizabeth, and since we have used the skip pattern as “Eliza” hence we got the output as “beth”.
We will create a text file that we have to read. Below is the Sample.txt file.
Sample.txt Hello we are learning about Scanner class. This is an example to read the file using scanner class.
Write a program that reads the above text file using the Scanner class.
package com.java.handson.io; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadTextFile { public static void main(String[] args) throws FileNotFoundException { File file = new File("src/com/java/handson/io/Sample.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } } Output: Hello we are learning about Scanner class. This is an example to read the file using scanner class.
In the above example, we have made use of the Scanner(File source) constructor. Firstly we have created a file class object using the path of the file and then we have passed this file reference to Scanner class object.
Once we have created a Scanner class object we check if the next token is available and if the next token is available then we use the nextLine() method that prints the input String till the end of the line. Since the file is having 2 lines hence the 2 lines are getting printed in the console. If we have to print individual tokens then we can make use of the next() method like below.
package com.java.handson.io; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadTextFile { public static void main(String[] args) throws FileNotFoundException { File file = new File("src/com/java/handson/io/Sample.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNext()) { System.out.println(scanner.next()); } } } Output: Hello we are learning about Scanner class. This is an example to read the file using scanner class.
package com.java.handson.io; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Scanner; public class ReadPath { public static void main(String[] args) throws IOException { File file = new File("src/com/java/handson/io/Sample.txt"); Path path = file.toPath(); Scanner scanner = new Scanner(path); while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } } Output: Hello we are learning about Scanner class. This is an example to read the file using scanner class.
This is all about the Scanner class and how to read user input using the Scanner class. If you have any questions on this topic please raise them in the comments section.
If you liked this article then please share this post and this website with your friends and colleagues so that they can learn Java and its frameworks in more depth.