With no added import statements to your code, your Java app has default access to all of the classes in the java.lang package. This includes classes such as:
String
System
Integer
Double
Math
Exception
Thread
However, to use any classes in packages other than java.lang in your code, an import is required.
The Scanner class is found in the java.util package, not java.lang.
Since the Scanner class is found outside of java.lang, you must either directly reference the java.util package every time you use the Scanner, or just add a single Scanner import statement to your Java file.
Phương thức của lớp Scanner trong Java
Dưới đây là một số phương thức quan trọng của lớp Scanner trong Java
STT
Tên phương thức
Mô tả
boolean nextBoolean ()
đọc giá trị boolean từ người dùng.
byte nextByte()
đọc giá trị byte từ người dùng
double nextDouble()
chấp nhận đầu vào trong kiểu dữ liệu kép từ người dùng.
float nextFloat()
nhận giá trị float từ người dùng.
int nextInt()
quét đầu vào kiểu int từ người dùng.
String nextLine()
đọc giá trị Chuỗi từ người dùng.
long nextLong()
đọc loại giá trị dài từ người dùng.
short nextShort()
đọc loại giá trị ngắn từ người dùng.
char next()
đọc đầu vào ký tự từ người dùng.
>>> Đọc thêm: Toán tử trong Java – Tìm hiểu các loại toán tử trong Java
Phương thức hasNextDataType của Java
Có những lúc chúng ta cần kiểm tra xem giá trị tiếp theo mà chúng ta đọc có thuộc một loại nào đó không hoặc đầu vào có EOF hay không. Sau đó, chúng ta kiểm tra xem đầu vào của máy quét có thuộc loại chúng ta muốn hay không với sự trợ giúp của các hàm hasNextXYZ () trong đó XYZ là kiểu dữ liệu mà chúng ta muốn sử dụng. Phương thức trả về true nếu máy quét có mã thông báo thuộc loại đó, ngược lại trả về false. Có một số phương thức boolean cho mỗi loại dữ liệu. Để kiểm tra xem mã thông báo tiếp theo của một loại dữ liệu cụ thể có sẵn trong đầu vào nhất định hay không. Bảng sau đây cho thấy chúng:
Phương thức
Mô tả
boolean hasNextBoolean ()
Phương pháp này kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu là Boolean bằng phương thức nextBoolean () hay không.
boolean hasNextByte ()
Phương pháp này kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu là Byte bằng cách sử dụng phương thức nextByte () hay không.
boolean hasNextDouble ()
Phương pháp này kiểm tra xem mã thông báo tiếp theo trong máy quét này có phải là đầu vào BigDecimal bằng cách sử dụng phương thức nextBigDecimal () hay không.
boolean hasNextFloat ()
Phương pháp này kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu là một Float bằng cách sử dụng phương thức nextFloat () hay không.
boolean hasNextInt ()
Phương thức này kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu là một int sử dụng phương thức nextInt () hay không.
boolean hasNextLine ()
Phương pháp này kiểm tra xem có dòng khác trong đầu vào của máy quét này hay không.
boolean hasNextLong ()
Phương thức này kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu là Long bằng phương thức nextLong () hay không.
Kết luận: Lớp Scanner là một cách hữu dụng giúp lập trình viên lấy đầu vào người dùng trong chương trình. Bài viết trên đã giới thiệu tới bạn về lớp Scanner trong Java và các phương thức và hàm tạo của lớp Scanner. Hy vọng bạn có thể hiểu rõ hơn về Scanner trong Java qua bài viết này. Tìm hiểu thêm về Java và các ngôn ngữ lập trình khác qua các khóa học lập trình tại T3H bạn nhé!
By Pankaj
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Java Scanner class is part of the java.util package. It was introduced in Java 1.5 release. The Scanner is mostly used to receive user input and parse them into primitive data types such as int, double or default String. It’s a utility class to parse data using regular expressions by generating tokens.
If you look at the Scanner class, there are many constructors.
Most of the constructors are using one of the three objects:
If you look at the second argument, it’s to specify a character set if you don’t want to use the default character set for parsing.
Let’s look at some of the most commonly used Scanner class methods.
There are many utility methods to check and directly parse the input token in int, short, long, byte, BigDecimal, etc.
Let’s look at some of the common usages of the Scanner class with sample code snippets.
This is the most common use of the Scanner class. We can instantiate with System.in as input source and read the user input.
// read user input Scanner sc = new Scanner(System.in); System.out.println("Please enter your name"); String name = sc.next(); System.out.println("Hello " + name); sc.close();
Output:
Please enter your name Pankaj Hello Pankaj
Well, it looks easy and working fine. But, the above code has an issue. Without reading the next section, can you check the code and try to identify it?
Let’s see what happens when I write my full name in the input.
Please enter your name Pankaj Kumar Hello Pankaj
Now you must have got it, it’s happening because whitespace is the delimiter. The scanner is breaking the input into two tokens – Pankaj and Kumar. But, we are calling the next() method just once, so only “Hello Pankaj” is printed.
How do we fix this?
It’s simple. We can change the delimiter to a newline character using the useDelimiter() method.
Scanner sc = new Scanner(System.in); sc.useDelimiter(System.getProperty("line.separator")); System.out.println("Please enter your name"); String name = sc.next(); System.out.println("Hello " + name); sc.close();
Let’s look at a simple example to read and parse CSV files using the scanner class. Let’s say, I have an employees.csv file with the following content.
1,Jane Doe,CEO 2,Mary Ann,CTO 3,John Lee,CFO
Let’s read the file and get a list of Employees in our Java program.
package com.journaldev.java; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ScannerExamples { public static void main(String[] args) throws IOException { // create scanner for the CSV file Scanner sc = new Scanner(new File("employees.csv")); // set delimiter as new line to read one line as a single token sc.useDelimiter(System.getProperty("line.separator")); // create the List of Employees List
emps = new ArrayList<>(); while (sc.hasNext()) { Employee emp = parseEmployeeData(sc.next()); emps.add(emp); } // close the scanner sc.close(); // print employee records System.out.println(emps); } private static Employee parseEmployeeData(String record) { // create scanner for the String record Scanner sc = new Scanner(record); // set delimiter as comma sc.useDelimiter(","); Employee emp = new Employee(); emp.setId(sc.nextInt()); emp.setName(sc.next()); emp.setRole(sc.next()); // close the scanner sc.close(); return emp; } } class Employee { private int id; private String name; private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } @Override public String toString() { return "Emp[" + id + "," + name + "," + role + "]"; } }
Let’s say we have a string source and we want to process only integers present in that. We can use the scanner with the non-digit regex to get only integers as tokens to process them.
//using regex to read only integers from a string source String data = "1a2b345c67d8,9#10"; Scanner sc1 = new Scanner(data); // setting non-digit regex as delimiter sc1.useDelimiter("\\D"); while(sc1.hasNext()) { System.out.println(sc1.next()); } // don't forget to close the scanner sc1.close();
Output:
1 2 345 67 8 9 10
Java Scanner is a utility class to read user input or process simple regex-based parsing of file or string source. But, for real-world applications, it’s better to use CSV parsers to parse CSV data rather than using the Scanner class for better performance.
Reference: API Doc, Regex in Java
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Useful tutorial even after four years.
– kiran
i need a simple program that it should take text as input using parser and analyse the text as output then it should perform AST using the output of parser
– mathi
Nice article.
– Manohar
Where is the Path class?
– mark
I want to read a method of java class line by line and do the analysis of each statement. Any idea how i can achieve it?
– Pravindrasingh
how to use scanner class with servlet?? it will work???
– karan patel
sir iam writing a program to extract email headers like From,to,Subject etc,how do i write it so that i can extract only lines followed by From: , To: and not the remaining text i tried Pattern.compile with scanner but not working
– shaun
i could not understand what is java File Scanner in line 54,i know Scanner but JavaFile Scanner
– shaun
Click below to sign up and get $200 of credit to try our products over 60 days!
Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Java is the most popular programming language owing to its flexibility and excellent library support. The Scanner class in Java emerges as a core element that allows user input across Java’s numerous classes. Let’s look at the complexities of the scanner in Java, grasp its capabilities, investigate the innumerable input types in multiple aspects, and discover its applications will provide you with a comprehensive knowledge of how to use this scanner class in Java efficiently.
How do you use the Java Scanner without an import?
Here’s an example of how to avoid a Java Scanner import and instead directly reference the package when the Scanner is used:
package com.mcnz.example; // Notice how the Java Scanner import is removed public class ScannerUserInput { public static void main(String[] args) { System.out.println(“How old are you?”); // With no Scanner import, an explicit java.util reference is needed java.util.Scanner stringScanner = new java.util.Scanner(System.in); String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); } }
Notice how the code becomes a bit more verbose, as the package reference adds bloat to the line of code where the Scanner is first declared.
Both the Java Scanner import and an explicit package reference are valid options to access the class. Which option a developer chooses comes down to which approach they believe makes their code the most readable and maintainable.
What is the Java Scanner?
The Java Scanner is a class in the Java Utilities Package, and it serves the purpose of creating bi-directional communication between the software and its user. In other words, it provides a way for the user to enter information that the software can use to inform its behavior.
This is a big deal since almost all software requires some degree of user interaction, and it needs a way to capture that data. The creators of the Java language considered that early on and provided the Scanner class to make this an easy process. Quite right, too, since it should be one of the easiest things to do, especially for software that requires a large amount of user input.
Those building websites with Java can use it to create a user sign-up/sign-in feature, ensuring that only the characters the developers deem safe can be entered. You can even use the Scanner to control data format before entering it into a database. The following video shows an example of how to use the Java Scanner class to perform a function.
How do you import the Java Scanner class?
There are two ways to implement the Java Scanner import: explicitly reference the
java.util.Scanner
package and class in the import, or do a wildcard import of
java.util.*
.
Here is how the two Java Scanner import options look:
The import statement must occur after the package declaration and before the class declaration.
How do you use the Java Scanner without an import?
Here’s an example of how to avoid a Java Scanner import and instead directly reference the package when the Scanner is used:
package com.mcnz.example; // Notice how the Java Scanner import is removed public class ScannerUserInput { public static void main(String[] args) { System.out.println(“How old are you?”); // With no Scanner import, an explicit java.util reference is needed java.util.Scanner stringScanner = new java.util.Scanner(System.in); String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); } }
Notice how the code becomes a bit more verbose, as the package reference adds bloat to the line of code where the Scanner is first declared.
Both the Java Scanner import and an explicit package reference are valid options to access the class. Which option a developer chooses comes down to which approach they believe makes their code the most readable and maintainable.
Nhập lớp Scanner trong Java
Để dùng những phương thức và chức năng của lớp Scanner, chúng ta cần nhập lớp vào chương trình Java của mình bằng cách nhập gói java.util bằng phương pháp dùng từ khóa import ở đầu mã.
Hai cách mà ta có thể làm như sau:
import java.util.Scanner;
//nhập lớp Scanner trong Java
import java.util.*;
//nhập hết những lớp của gói trong
java.util
How to Use Scanner in Java
Let’s consider the Scanner from the view of a game development standpoint, which is transferable to other software development. Considering the character creation step in a video game, most require input. Typically during this step, the game will prompt the user for information; this is often a name, height, age, etc.
Once the user enters this information, the game uses it to perform specific actions, like inserting the character’s name into the speech in the game or setting the character’s height.
Now, let’s look at an example of how this works with the Java Scanner.
class Main {public static void main(String[] args) {Scanner userInput = new Scanner(System.in);System.out.println(“Please tell us your name:”);// String inputString name = userInput.nextLine();//Pint user inputSystem.out.println(“Welcome to Gallifrey: ” + name);}}
The code above would prompt the user to input their name, and the user would type and enter their text; let’s assume the user entered Doctor Who. Once that action finishes, the code above would print “Welcome to Gallifrey, Doctor Who” to the interface. With this example in mind, it becomes easier to understand how the methods above fit into place with this class.
For example, instead of calling the nextLine() method on our input Scanner object, you could use the next() method.
// String inputString name = myObj.next();
This line of code would have only returned the string Doctor dropping the rest of the string. This behavior can be beneficial for controlling the data flow to and from the software. Check out the next video to learn more about how this process can be used.
What happens if you don’t import the Scanner?
If you attempt to use the Scanner class but fail to add an import, or don’t explicitly reference the package and the class together, you will encounter the following error:
Error: Scanner cannot be resolved to a type
The “cannot be resolved to a type” compile time error may sound somewhat confusing to a new developer. All it’s saying is that you have referenced a class that is outside of any package referenced through an import statement.
If you get the “Scanner cannot be resolved to a type” error message, just add the Java Scanner import statement to your code, or explicitly reference the package when you use the Scanner class in your code.
By Pankaj
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Java Scanner class is part of the java.util package. It was introduced in Java 1.5 release. The Scanner is mostly used to receive user input and parse them into primitive data types such as int, double or default String. It’s a utility class to parse data using regular expressions by generating tokens.
If you look at the Scanner class, there are many constructors.
Most of the constructors are using one of the three objects:
If you look at the second argument, it’s to specify a character set if you don’t want to use the default character set for parsing.
Let’s look at some of the most commonly used Scanner class methods.
There are many utility methods to check and directly parse the input token in int, short, long, byte, BigDecimal, etc.
Let’s look at some of the common usages of the Scanner class with sample code snippets.
This is the most common use of the Scanner class. We can instantiate with System.in as input source and read the user input.
// read user input Scanner sc = new Scanner(System.in); System.out.println("Please enter your name"); String name = sc.next(); System.out.println("Hello " + name); sc.close();
Output:
Please enter your name Pankaj Hello Pankaj
Well, it looks easy and working fine. But, the above code has an issue. Without reading the next section, can you check the code and try to identify it?
Let’s see what happens when I write my full name in the input.
Please enter your name Pankaj Kumar Hello Pankaj
Now you must have got it, it’s happening because whitespace is the delimiter. The scanner is breaking the input into two tokens – Pankaj and Kumar. But, we are calling the next() method just once, so only “Hello Pankaj” is printed.
How do we fix this?
It’s simple. We can change the delimiter to a newline character using the useDelimiter() method.
Scanner sc = new Scanner(System.in); sc.useDelimiter(System.getProperty("line.separator")); System.out.println("Please enter your name"); String name = sc.next(); System.out.println("Hello " + name); sc.close();
Let’s look at a simple example to read and parse CSV files using the scanner class. Let’s say, I have an employees.csv file with the following content.
1,Jane Doe,CEO 2,Mary Ann,CTO 3,John Lee,CFO
Let’s read the file and get a list of Employees in our Java program.
package com.journaldev.java; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ScannerExamples { public static void main(String[] args) throws IOException { // create scanner for the CSV file Scanner sc = new Scanner(new File("employees.csv")); // set delimiter as new line to read one line as a single token sc.useDelimiter(System.getProperty("line.separator")); // create the List of Employees List
emps = new ArrayList<>(); while (sc.hasNext()) { Employee emp = parseEmployeeData(sc.next()); emps.add(emp); } // close the scanner sc.close(); // print employee records System.out.println(emps); } private static Employee parseEmployeeData(String record) { // create scanner for the String record Scanner sc = new Scanner(record); // set delimiter as comma sc.useDelimiter(","); Employee emp = new Employee(); emp.setId(sc.nextInt()); emp.setName(sc.next()); emp.setRole(sc.next()); // close the scanner sc.close(); return emp; } } class Employee { private int id; private String name; private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } @Override public String toString() { return "Emp[" + id + "," + name + "," + role + "]"; } }
Let’s say we have a string source and we want to process only integers present in that. We can use the scanner with the non-digit regex to get only integers as tokens to process them.
//using regex to read only integers from a string source String data = "1a2b345c67d8,9#10"; Scanner sc1 = new Scanner(data); // setting non-digit regex as delimiter sc1.useDelimiter("\\D"); while(sc1.hasNext()) { System.out.println(sc1.next()); } // don't forget to close the scanner sc1.close();
Output:
1 2 345 67 8 9 10
Java Scanner is a utility class to read user input or process simple regex-based parsing of file or string source. But, for real-world applications, it’s better to use CSV parsers to parse CSV data rather than using the Scanner class for better performance.
Reference: API Doc, Regex in Java
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Useful tutorial even after four years.
– kiran
i need a simple program that it should take text as input using parser and analyse the text as output then it should perform AST using the output of parser
– mathi
Nice article.
– Manohar
Where is the Path class?
– mark
I want to read a method of java class line by line and do the analysis of each statement. Any idea how i can achieve it?
– Pravindrasingh
how to use scanner class with servlet?? it will work???
– karan patel
sir iam writing a program to extract email headers like From,to,Subject etc,how do i write it so that i can extract only lines followed by From: , To: and not the remaining text i tried Pattern.compile with scanner but not working
– shaun
i could not understand what is java File Scanner in line 54,i know Scanner but JavaFile Scanner
– shaun
Click below to sign up and get $200 of credit to try our products over 60 days!
Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Java User Input (Scanner)
Example
The Java.util package contains the scanner in Java, which links the program and the input stream. It offers ways to read and interpret many kinds of data from the standard input stream (System.in), including strings, characters, integers, and doubles. By default, this stream is attached to the keyboard, ensuring the program communicates with the user via the console.
Let’s go over an example to understand how the Scanner class captures and handles user input. In this example, we will write a Java program that assembles data on a person and outputs the information to the console.
// Java program to read data of various types using Scanner
// class.
import java.util.Scanner;
public class ScannerDemo1 {
public static void main(String[] args)
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(:System.in);
// String input
String name = sc.nextLine();
linksr gender = sc.next().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();
// Print the values to check if the input was
// correctly obtained.
System.out.println(“Name: ” + name);
System.out.println(“Gender: ” + gender);
System.out.println(“Age: ” + age);
System.out.println(“Mobile Number: ” + mobileNo);
System.out.println(“CGPA: ” + cgpa);
Input
1 2 3 4 5
Output
Mean: 3
How do you import the Java Scanner class?
There are two ways to implement the Java Scanner import: explicitly reference the
java.util.Scanner
package and class in the import, or do a wildcard import of
java.util.*
.
Here is how the two Java Scanner import options look:
The import statement must occur after the package declaration and before the class declaration.
Java
import
java.util.Scanner;
public
class
ScannerDemo2 {
public
static
void
main(String[] args)
Scanner sc =
new
Scanner(System.in);
int
sum =
, count =
while
(sc.hasNextInt()) {
int
num = sc.nextInt();
sum += num;
count++;
if
(count >
) {
int
mean = sum / count;
System.out.println(
"Mean: "
+ mean);
else
System.out.println(
"No integers were input. Mean cannot be calculated."
);
Input
1 2 3 4 5
Output
Mean: 3
Important Points About Java Scanner Class
To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
To read strings, we use nextLine().
To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example, Suppose there is an input string: How are youIn this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods.
Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:
Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks
Last Updated :
13 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment…
Java Scanner import
Input Types
In the example above, we used the
nextLine()
method, which is used to read Strings. To read other types, look at the table below:
Method
Description
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Enter name, age and salary:"); // String input String name = myObj.nextLine(); // Numerical input int age = myObj.nextInt(); double salary = myObj.nextDouble(); // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } }
Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like “InputMismatchException”).
You can read more about exceptions and how to handle errors in the Exceptions chapter.
In Java, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings.
Using the Scanner class in Java is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.
How to Start Scanning for User Input With Java
You’ve learned a lot throughout this post, such as the Java Scanner class and what it does. You’ve also learned how to import it and understand the methods that come with it. You’ve even seen a simple yet effective example of how you could use it to collect a character name from a user.
Java Scanner import
Example 4: Read BigInteger and BigDecimal
import java.math.BigDecimal; import java.math.BigInteger; import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter a big integer: "); // reads the big integer BigInteger value1 = input.nextBigInteger(); System.out.println("Using nextBigInteger(): " + value1); System.out.print("Enter a big decimal: "); // reads the big decimal BigDecimal value2 = input.nextBigDecimal(); System.out.println("Using nextBigDecimal(): " + value2); input.close(); } }
Output
Enter a big integer: 987654321 Using nextBigInteger(): 987654321 Enter a big decimal: 9.55555 Using nextBigDecimal(): 9.55555
In the above example, we have used the
java.math.BigInteger
and
java.math.BigDecimal
package to read
BigInteger
and
BigDecimal
respectively.
Java Scanner Class Constructors
SN
Constructor
Description
1)
Scanner(File source)
It constructs a new Scanner that produces values scanned from the specified file.
2)
Scanner(File source, String charsetName)
It constructs a new Scanner that produces values scanned from the specified file.
3)
Scanner(InputStream source)
It constructs a new Scanner that produces values scanned from the specified input stream.
4)
Scanner(InputStream source, String charsetName)
It constructs a new Scanner that produces values scanned from the specified input stream.
5)
Scanner(Readable source)
It constructs a new Scanner that produces values scanned from the specified source.
6)
Scanner(String source)
It constructs a new Scanner that produces values scanned from the specified string.
7)
Scanner(ReadableByteChannel source)
It constructs a new Scanner that produces values scanned from the specified channel.
It constructs a new Scanner that produces values scanned from the specified channel.
9)
Scanner(Path source)
It constructs a new Scanner that produces values scanned from the specified file.
10)
Scanner(Path source, String charsetName)
It constructs a new Scanner that produces values scanned from the specified file.
Example 5: Java Scanner nextLine()
import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // reads the entire line String value = input.nextLine(); System.out.println("Using nextLine(): " + value); input.close(); } }
Output
Enter your name: Jonny Walker Using nextLine(): Jonny Walker
In the first example, we have used the
nextLine()
method to read a string from the user.
Unlike
next()
, the
nextLine()
method reads the entire line of input including spaces. The method is terminated when it encounters a next line character,
\n
.
To learn more, visit Java Scanner skipping the nextLine().
Example 4: Java Scanner next()
import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // reads the entire word String value = input.next(); System.out.println("Using next(): " + value); input.close(); } }
Output
Enter your name: Jonny Walker Using next(): Jonny
In the above example, we have used the
next()
method to read a string from the user.
Here, we have provided the full name. However, the
next()
method only reads the first name.
This is because the
next()
method reads input up to the whitespace character. Once the whitespace is encountered, it returns the string (excluding the whitespace).
Java Scanner import example
Here’s an example of an application that uses an explicit Java Scanner import so that we can make the program interactive with user input:
package com.mcnz.example; import java.util.Scanner; public class ScannerUserInput { public static void main(String[] args) { // String input with the Java Scanner System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); } }
Java Scanner import example
Here’s an example of an application that uses an explicit Java Scanner import so that we can make the program interactive with user input:
package com.mcnz.example; import java.util.Scanner; public class ScannerUserInput { public static void main(String[] args) { // String input with the Java Scanner System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); } }
Example 1: Read a Line of Text Using Scanner
import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // takes input from the keyboard String name = input.nextLine(); // prints the name System.out.println("My name is " + name); // closes the scanner input.close(); } }
Output
Enter your name: Kelvin My name is Kelvin
In the above example, notice the line
Scanner input = new Scanner(System.in);
Here, we have created an object of
Scanner
named input.
The
System.in
parameter is used to take input from the standard input. It works just like taking inputs from the keyboard.
We have then used the
nextLine()
method of the
Scanner
class to read a line of text from the user.
Now that you have some idea about
Scanner
, let’s explore more about it.
Java Scanner Methods to Take Input
The
Scanner
class provides various methods that allow us to read inputs of different types.
Method
Description
reads an
reads a
reads a
reads a line of text from the user
reads a word from the user
reads a
reads a
reads a
reads a
Example 3: Java Scanner nextDouble()
import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter Double value: "); // reads the double value double value = input.nextDouble(); System.out.println("Using nextDouble(): " + value); input.close(); } }
Output
Enter Double value: 33.33 Using nextDouble(): 33.33
In the above example, we have used the
nextDouble()
method to read a floating-point value.
Working of Java Scanner
The
Scanner
class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example,
Suppose there is an input string:
He is 22
In this case, the scanner object will read the entire line and divides the string into tokens: “He”, “is” and “22”. The object then iterates over each token and reads each token using its different methods.
Note: By default, whitespace is used to divide tokens.
Also Read: Basic Input/Output
Lớp Scanner trong Java – Phương thức và hàm tạo lớp Scanner trong Java
03/11/2021 13:29
Trong những bài viết trước, chúng ta tìm hiểu về từ khóa triển khai trong Java. Trong bài viết này, chúng ta sẽ thảo luận về một lớp đặc biệt trong Java đó là Lớp Scanner Java. Chắc hẳn, bạn đã biết cách in thông tin lên màn hình của người dùng bằng chương trình Java, nhưng nếu có nhu sử dụng lấy đầu vào từ người dùng trong khi viết chương trình, bạn có thể sử dụng lớp Scanner trong Java. Trong bài viết này, chúng ta sẽ tìm hiểu về lớp này cùng phương thức của nó và các ví dụ đi kèm.
Java User Input
The
Scanner
class is used to get
user input, and it is found in the
java.util
package.
To use the
Scanner
class, create an object of the class and use any of the available methods found in the
Scanner
class documentation.
In our example, we will use the
nextLine()
method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner class class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input } }
If you don’t know what a package is, read our Java Packages Tutorial.
How to Import Scanner in Java
Importing Scanner for use in your code is simple and only requires a singular line of code. The Scanner class comes in a commonly used package aptly named the utilities package. At the top of every file is where all imports occur, and the utils import will often be one of the first imports you make.
import java.util.Scanner;
And that’s it; importing the Scanner class is as easy as it can get. Once you’ve imported the Scanner class, you can begin to use it in your code. Next, let’s look at some of the most common methods used with the Scanner class, then we can dive into some code examples.
Java Scanner Input Types
At the center of the Scanner class in Java lies its capability to parse diverse input types, ensuring seamless user interaction. To this end, the class provides some methods, each of these are tailored to handle a specific data type. Do read about these methods to understand their utilization better:
nextBoolean () – Designed to interpret the next token as a boolean value, this method deciphers and returns either “true” or “false” based on the user’s input.
nextByte() – When dealing with numerical data within the byte range, the nextByte() method steps in. It captures the next token as a byte value, catering to the precision requirements.
nextDouble() – For scenarios involving double-precision floating-point values, the nextDouble() method is indispensable. It diligently translates the upcoming token into a double data type, maintaining the accuracy of the input.
nextFloat() – The next Float() method finds its purpose in capturing single- precision floating-point values. This method is instrumental when accuracy matters and the input demands adherence to float constraints.
nextInt( )-In integer input, nextInt() emerges as a stalwart. It efficiently processes the next token as an integer, catering to applications requiring whole number values.
nextLine() – Often, user input encompasses more than just numerical data. In these cases, the next line () method proves invaluable, capturing entire lines of text, along with spaces and characters.
nextLong() – For handling extended integer values beyond the scope of nextInt(), the nextLong() method is brought into play. It aptly captures long integer values with precision.
nextShort() – When a narrower range of short integer values is on the horizon, nextShort() takes the stage. It seamlessly captures these values, catering to specific application requirements.
Sử dụng lớp Scanner trong Java
Sau khi nhập lớp Scanner, chúng ta phải lấy thể hiện của lớp này để đọc đầu vào từ người dùng. Chúng ta sẽ tạo một cá thể và chuyển Input Stream System.in trong khi tạo cá thể như sau:
Scanner ScannerObject = new scanner (System.in);
Ởđây, bằng cách viết Scanner scannerObject, chúng ta đang khai báo scannerObject là đối tượng của lớp máy quét. System.in biểu thị rằng đầu vào sẽ được cấp cho Hệ thống.
>>> Đọc thêm: Tham khảo khóa học lập trình Java
Key Points About Java Scanner Class
Versatile Input Handling – The Scanner class simplifies the intricacies of user input handling by offering methods tailored to diverse data types.
Library Inclusion – As part of the java.util package, the Scanner class doesn’t necessitate additional imports, ensuring its accessibility.
Input Source Flexibility – The Scanner class is designed to read input from various sources, including the keyboard (System.in) and files.
Class Hierarchy – Unlike being a superclass, the Scanner class is a prominent member of java.util package, providing input parsing capabilities.
Comprehensive Library – The Scanner class library spans methods catering to primitive data types, strings, and even custom patterns, enhancing its applicability.
Hàm tạo của lớp Scanner trong Java
STT
Hàm tạo
Mô tả
Scanner (Nguồn tệp)
làm đối tượng Scanner tạo ra những giá trị được quét từ tệp được chỉ định
Scanner (File source, String charsetName)
xây dựng đối tượng Scanner tạo ra các giá trị được quét từ tệp được chỉ định
Scanner (InputStream source)
tạo ra 1 đối tượng Scanner mới tạo ra các giá trị được quét từ luồng đầu vào được chỉ định.
Scanner (InputStream source, String charsetName)
tạo 1 Scanner mới tạo ra các giá trị được quét từ luồng đầu vào được chỉ định.
Scanner (Readable source)
tạo 1 Scanner mới tạo ra các giá trị được quét từ nguồn được chỉ định.
Scanner (String source)
tạo 1 Scanner mới tạo ra các giá trị được quét từ chuỗi được chỉ định.
Scanner (ReadableByteChannel source)
tạo 1 Scanner mới tạo ra các giá trị được quét từ kênh được chỉ định.
tạo 1 Máy quét mới tạo ra các giá trị được quét từ kênh được chỉ định.
Scanner (Path source)
tạo 1 Scanner mới tạo ra các giá trị được quét từ tệp được chỉ định.
10
Scanner (Path source, String charsetName)
tạo 1 Scanner mới tạo ra các giá trị được quét từ tệp được chỉ định
FAQs
Which Scanner class is used to take input in Java?
The java.util.Scanner class is exclusively used for taking input in Java. Its specialized methods cater to a wide range of input types.
Is Scanner a superclass?
No, the Scanner class does not serve as a superclass. It holds the status of a standalone class within the java.util package, designed for input processing.
What is the library of Scanner in Java?
The Scanner class library is a comprehensive set of processes for reading different input types like booleans, bytes, doubles, floats, ints, longs, shorts, and strings.
What happens if you don’t import the Scanner?
If you attempt to use the Scanner class but fail to add an import, or don’t explicitly reference the package and the class together, you will encounter the following error:
Error: Scanner cannot be resolved to a type
The “cannot be resolved to a type” compile time error may sound somewhat confusing to a new developer. All it’s saying is that you have referenced a class that is outside of any package referenced through an import statement.
If you get the “Scanner cannot be resolved to a type” error message, just add the Java Scanner import statement to your code, or explicitly reference the package when you use the Scanner class in your code.
public final class Scanner extends Object implements Iterator
, Closeable
A
Scanner
breaks its input into tokens using a
delimiter pattern, which by default matches whitespace. The resulting
tokens may then be converted into values of different types using the
various next methods.
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in); int i = sc.nextInt();
As another example, this code allows
long
types to be
assigned from entries in a file
myNumbers
:
Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); }
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();
prints the following output:
1 2 red blue
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input); s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); MatchResult result = s.match(); for (int i=1; i<=result.groupCount(); i++) System.out.println(result.group(i)); s.close();
The default whitespace delimiter used
by a scanner is as recognized by
Character
.
isWhitespace
. The
reset()
method will reset the value of the scanner’s delimiter to the default
whitespace delimiter regardless of whether it was previously changed.
A scanning operation may block waiting for input.
The
next()
and
hasNext()
methods and their
primitive-type companion methods (such as
nextInt()
and
hasNextInt()
) first skip any input that matches the delimiter
pattern, and then attempt to return the next token. Both hasNext
and next methods may block waiting for further input. Whether a
hasNext method blocks has no connection to whether or not its
associated next method will block.
The
findInLine(java.lang.String)
,
findWithinHorizon(java.lang.String, int)
, and
skip(java.util.regex.Pattern)
methods operate independently of the delimiter pattern. These methods will
attempt to match the specified pattern with no regard to delimiters in the
input and thus can be used in special circumstances where delimiters are
not relevant. These methods may block waiting for more input.
When a scanner throws an
InputMismatchException
, the scanner
will not pass the token that caused the exception, so that it may be
retrieved or skipped via some other method.
Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern “\\s+” will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern “\\s” could return empty tokens since it only passes one space at a time.
A scanner can read text from any object which implements the
Readable
interface. If an invocation of the underlying
readable’s
Readable.read(java.nio.CharBuffer)
method throws an
IOException
then the scanner assumes that the end of the input
has been reached. The most recent IOException thrown by the
underlying readable can be retrieved via the
ioException()
method.
When a
Scanner
is closed, it will close its input source
if the source implements the
Closeable
interface.
A
Scanner
is not safe for multithreaded use without
external synchronization.
Unless otherwise mentioned, passing a
null
parameter into
any method of a
Scanner
will cause a
NullPointerException
to be thrown.
A scanner will default to interpreting numbers as decimal unless a
different radix has been set by using the
useRadix(int)
method. The
reset()
method will reset the value of the scanner’s radix to
10
regardless of whether it was previously changed.
An instance of this class is capable of scanning numbers in the standard
formats as well as in the formats of the scanner’s locale. A scanner’s
initial locale is the value returned by the
Locale.getDefault(Locale.Category.FORMAT)
method; it may be changed via the
useLocale(java.util.Locale)
method. The
reset()
method will reset the value of the
scanner’s locale to the initial locale regardless of whether it was
previously changed.
The localized formats are defined in terms of the following parameters,
which for a particular locale are taken from that locale’s
DecimalFormat
object, df, and its and
DecimalFormatSymbols
object,
dfs.
LocalGroupSeparator
The character used to separate thousands groups, i.e., dfs.
getGroupingSeparator()
LocalDecimalSeparator
The character used for the decimal point, i.e., dfs.
getDecimalSeparator()
LocalPositivePrefix
The string that appears before a positive number (may be empty), i.e., df.
getPositivePrefix()
LocalPositiveSuffix
The string that appears after a positive number (may be empty), i.e., df.
getPositiveSuffix()
LocalNegativePrefix
The string that appears before a negative number (may be empty), i.e., df.
getNegativePrefix()
LocalNegativeSuffix
The string that appears after a negative number (may be empty), i.e., df.
getNegativeSuffix()
LocalNaN
The string that represents not-a-number for floating-point values, i.e., dfs.
getNaN()
LocalInfinity
The string that represents infinity for floating-point values, i.e., dfs.
getInfinity()
The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10).
Character.isDigit(c) returns true
Whitespace is not significant in the above regular expressions.
Constructor and Description
Constructs a new
Constructs a new
Constructs a new
Constructs a new
Constructs a new
Constructs a new
Constructs a new
Constructs a new
Constructs a new
Constructs a new
Modifier and Type
Method and Description
Closes this scanner.
Returns the
Attempts to find the next occurrence of the specified pattern ignoring delimiters.
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
Attempts to find the next occurrence of the specified pattern.
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
Returns true if this scanner has another token in its input.
Returns true if the next complete token matches the specified pattern.
Returns true if the next token matches the pattern constructed from the specified string.
Returns true if the next token in this scanner’s input can be interpreted as a
Returns true if the next token in this scanner’s input can be interpreted as a
Returns true if the next token in this scanner’s input can be interpreted as a
Returns true if the next token in this scanner’s input can be interpreted as a boolean value using a case insensitive pattern created from the string “true|false”.
Returns true if the next token in this scanner’s input can be interpreted as a byte value in the default radix using the
Returns true if the next token in this scanner’s input can be interpreted as a byte value in the specified radix using the
Returns true if the next token in this scanner’s input can be interpreted as a double value using the
Returns true if the next token in this scanner’s input can be interpreted as a float value using the
Returns true if the next token in this scanner’s input can be interpreted as an int value in the default radix using the
Returns true if the next token in this scanner’s input can be interpreted as an int value in the specified radix using the
Returns true if there is another line in the input of this scanner.
Returns true if the next token in this scanner’s input can be interpreted as a long value in the default radix using the
Returns true if the next token in this scanner’s input can be interpreted as a long value in the specified radix using the
Returns true if the next token in this scanner’s input can be interpreted as a short value in the default radix using the
Returns true if the next token in this scanner’s input can be interpreted as a short value in the specified radix using the
Returns the
Returns this scanner’s locale.
Returns the match result of the last scanning operation performed by this scanner.
Finds and returns the next complete token from this scanner.
Returns the next token if it matches the specified pattern.
Returns the next token if it matches the pattern constructed from the specified string.
Scans the next token of the input as a
Scans the next token of the input as a
Scans the next token of the input as a
Scans the next token of the input into a boolean value and returns that value.
Scans the next token of the input as a byte.
Scans the next token of the input as a byte.
Scans the next token of the input as a double.
Scans the next token of the input as a float.
Scans the next token of the input as an int.
Scans the next token of the input as an int.
Advances this scanner past the current line and returns the input that was skipped.
Scans the next token of the input as a long.
Scans the next token of the input as a long.
Scans the next token of the input as a short.
Scans the next token of the input as a short.
Returns this scanner’s default radix.
The remove operation is not supported by this implementation of
Resets this scanner.
Skips input that matches the specified pattern, ignoring delimiters.
Skips input that matches a pattern constructed from the specified string.
Returns the string representation of this
Sets this scanner’s delimiting pattern to the specified pattern.
Sets this scanner’s delimiting pattern to a pattern constructed from the specified
Sets this scanner’s locale to the specified locale.
Sets this scanner’s default radix to the specified radix.
Scannerthat produces values scanned from the specified source.
source- A character source implementing the
Readableinterface
public Scanner(InputStream source)
Scannerthat produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform's default charset.
source- An input stream to be scanned
public Scanner(InputStream source, String charsetName)
Scannerthat produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the specified charset.
source- An input stream to be scanned
charsetName- The encoding type used to convert bytes from the stream into characters to be scanned
IllegalArgumentException- if the specified character set does not exist
public Scanner(File source) throws FileNotFoundException
Scannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
source- A file to be scanned
FileNotFoundException- if source is not found
public Scanner(File source, String charsetName) throws FileNotFoundException
Scannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.
source- A file to be scanned
charsetName- The encoding type used to convert bytes from the file into characters to be scanned
FileNotFoundException- if source is not found
IllegalArgumentException- if the specified encoding is not found
public Scanner(Path source) throws IOException
Scannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
source- the path to the file to be scanned
IOException- if an I/O error occurs opening source
public Scanner(Path source, String charsetName) throws IOException
Scannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.
source- the path to the file to be scanned
charsetName- The encoding type used to convert bytes from the file into characters to be scanned
IOException- if an I/O error occurs opening source
IllegalArgumentException- if the specified encoding is not found
public Scanner(String source)
Scannerthat produces values scanned from the specified string.
source- A string to scan
public Scanner(ReadableByteChannel source)
Scannerthat produces values scanned from the specified channel. Bytes from the source are converted into characters using the underlying platform's default charset.
source- A channel to scan
public Scanner(ReadableByteChannel source, String charsetName)
Scannerthat produces values scanned from the specified channel. Bytes from the source are converted into characters using the specified charset.
source- A channel to scan
charsetName- The encoding type used to convert bytes from the channel into characters to be scanned
IllegalArgumentException- if the specified character set does not exist
public void close()
If this scanner has not yet been closed then if its underlying
readable also implements the
Closeable
interface then the readable’s close method
will be invoked. If this scanner is already closed then invoking this
method will have no effect.
Attempting to perform search operations after a scanner has
been closed will result in an
IllegalStateException
.
closein interface
Closeable
closein interface
AutoCloseable
public IOException ioException()
IOExceptionlast thrown by this
Scanner's underlying
Readable. This method returns
nullif no such exception exists.
public Pattern delimiter()
Patternthis
Scanneris currently using to match delimiters.
public Scanner useDelimiter(Pattern pattern)
pattern- A delimiting pattern
public Scanner useDelimiter(String pattern)
String.
An invocation of this method of the form useDelimiter(pattern) behaves in exactly the same way as the invocation useDelimiter(Pattern.compile(pattern)).
Invoking the
reset()
method will set the scanner’s delimiter
to the default.
pattern- A string specifying a delimiting pattern
public Locale locale()
A scanner’s locale affects many elements of its default primitive matching regular expressions; see localized numbers above.
public Scanner useLocale(Locale locale)
A scanner’s locale affects many elements of its default primitive matching regular expressions; see localized numbers above.
Invoking the
reset()
method will set the scanner’s locale to
the initial locale.
locale- A string specifying the locale to use
public int radix()
A scanner’s radix affects elements of its default number matching regular expressions; see localized numbers above.
public Scanner useRadix(int radix)
A scanner’s radix affects elements of its default number matching regular expressions; see localized numbers above.
If the radix is less than
Character.MIN_RADIX
or greater than
Character.MAX_RADIX
, then an
IllegalArgumentException
is thrown.
Invoking the
reset()
method will set the scanner’s radix to
10
.
radix- The radix to use when scanning numbers
IllegalArgumentException- if radix is out of range
public MatchResult match()
IllegalStateExceptionif no match has been performed, or if the last match was not successful.
The various
next
methods of
Scanner
make a match result available if they complete without throwing an
exception. For instance, after an invocation of the
nextInt()
method that returned an int, this method returns a
MatchResult
for the search of the
Integer regular expression
defined above. Similarly the
findInLine(java.lang.String)
,
findWithinHorizon(java.lang.String, int)
, and
skip(java.util.regex.Pattern)
methods will make a
match available if they succeed.
IllegalStateException- If no match result is available
public String toString()
Returns the string representation of this
Scanner
. The
string representation of a
Scanner
contains information
that may be useful for debugging. The exact format is unspecified.
public boolean hasNext()
hasNextin interface
Iterator
IllegalStateException- if this scanner is closed
Iterator
public String next()
hasNext()returned
true.
nextin interface
Iterator
NoSuchElementException- if no more tokens are available
IllegalStateException- if this scanner is closed
Iterator
public void remove()
Iterator.
removein interface
Iterator
UnsupportedOperationException- if this method is invoked.
Iterator
public boolean hasNext(String pattern)
An invocation of this method of the form hasNext(pattern) behaves in exactly the same way as the invocation hasNext(Pattern.compile(pattern)).
pattern- a string specifying the pattern to scan
IllegalStateException- if this scanner is closed
public String next(String pattern)
An invocation of this method of the form next(pattern) behaves in exactly the same way as the invocation next(Pattern.compile(pattern)).
pattern- a string specifying the pattern to scan
NoSuchElementException- if no such tokens are available
IllegalStateException- if this scanner is closed
public boolean hasNext(Pattern pattern)
pattern- the pattern to scan for
IllegalStateException- if this scanner is closed
public String next(Pattern pattern)
hasNext(Pattern)returned
true. If the match is successful, the scanner advances past the input that matched the pattern.
pattern- the pattern to scan for
NoSuchElementException- if no more tokens are available
IllegalStateException- if this scanner is closed
public boolean hasNextLine()
IllegalStateException- if this scanner is closed
public String nextLine()
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
NoSuchElementException- if no line was found
IllegalStateException- if this scanner is closed
public String findInLine(String pattern)
An invocation of this method of the form findInLine(pattern) behaves in exactly the same way as the invocation findInLine(Pattern.compile(pattern)).
pattern- a string specifying the pattern to search for
IllegalStateException- if this scanner is closed
public String findInLine(Pattern pattern)
nullis returned and the scanner's position is unchanged. This method may block waiting for input that matches the pattern.
Since this method continues to search through the input looking for the specified pattern, it may buffer all of the input searching for the desired token if no line separators are present.
pattern- the pattern to scan for
IllegalStateException- if this scanner is closed
public String findWithinHorizon(String pattern, int horizon)
An invocation of this method of the form findWithinHorizon(pattern) behaves in exactly the same way as the invocation findWithinHorizon(Pattern.compile(pattern, horizon)).
pattern- a string specifying the pattern to search for
horizon- the search horizon
IllegalStateException- if this scanner is closed
IllegalArgumentException- if horizon is negative
public String findWithinHorizon(Pattern pattern, int horizon)
This method searches through the input up to the specified search horizon, ignoring delimiters. If the pattern is found the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected then the null is returned and the scanner’s position remains unchanged. This method may block waiting for input that matches the pattern.
A scanner will never search more than
horizon
code
points beyond its current position. Note that a match may be clipped
by the horizon; that is, an arbitrary match result may have been
different if the horizon had been larger. The scanner treats the
horizon as a transparent, non-anchoring bound (see
Matcher.useTransparentBounds(boolean)
and
Matcher.useAnchoringBounds(boolean)
).
If horizon is , then the horizon is ignored and
this method continues to search through the input looking for the
specified pattern without bound. In this case it may buffer all of
the input searching for the pattern.
If horizon is negative, then an IllegalArgumentException is thrown.
pattern- the pattern to scan for
horizon- the search horizon
IllegalStateException- if this scanner is closed
IllegalArgumentException- if horizon is negative
public Scanner skip(Pattern pattern)
If a match to the specified pattern is not found at the current position, then no input is skipped and a NoSuchElementException is thrown.
Since this method seeks to match the specified pattern starting at the scanner’s current position, patterns that can match a lot of input (“.*”, for example) may cause the scanner to buffer a large amount of input.
Note that it is possible to skip something without risking a
NoSuchElementException
by using a pattern that can
match nothing, e.g.,
sc.skip("[ \t]*")
.
pattern- a string specifying the pattern to skip over
NoSuchElementException- if the specified pattern is not found
IllegalStateException- if this scanner is closed
public Scanner skip(String pattern)
An invocation of this method of the form skip(pattern) behaves in exactly the same way as the invocation skip(Pattern.compile(pattern)).
pattern- a string specifying the pattern to skip over
IllegalStateException- if this scanner is closed
public boolean hasNextBoolean()
IllegalStateException- if this scanner is closed
public boolean nextBoolean()
InputMismatchExceptionif the next token cannot be translated into a valid boolean value. If the match is successful, the scanner advances past the input that matched.
InputMismatchException- if the next token is not a valid boolean
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public boolean hasNextByte()
nextByte()method. The scanner does not advance past any input.
IllegalStateException- if this scanner is closed
public boolean hasNextByte(int radix)
nextByte()method. The scanner does not advance past any input.
radix- the radix used to interpret the token as a byte value
IllegalStateException- if this scanner is closed
public byte nextByte()
An invocation of this method of the form
nextByte() behaves in exactly the same way as the
invocation nextByte(radix), where
radix
is the default radix of this scanner.
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public byte nextByte(int radix)
InputMismatchExceptionif the next token cannot be translated into a valid byte value as described below. If the translation is successful, the scanner advances past the input that matched.
If the next token matches the Integer regular expression defined
above then the token is converted into a byte value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via
Character.digit
, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to
Byte.parseByte
with the
specified radix.
radix- the radix used to interpret the token as a byte value
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public boolean hasNextShort()
nextShort()method. The scanner does not advance past any input.
IllegalStateException- if this scanner is closed
public boolean hasNextShort(int radix)
nextShort()method. The scanner does not advance past any input.
radix- the radix used to interpret the token as a short value
IllegalStateException- if this scanner is closed
public short nextShort()
An invocation of this method of the form
nextShort() behaves in exactly the same way as the
invocation nextShort(radix), where
radix
is the default radix of this scanner.
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public short nextShort(int radix)
InputMismatchExceptionif the next token cannot be translated into a valid short value as described below. If the translation is successful, the scanner advances past the input that matched.
If the next token matches the Integer regular expression defined
above then the token is converted into a short value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via
Character.digit
, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to
Short.parseShort
with the
specified radix.
radix- the radix used to interpret the token as a short value
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public boolean hasNextInt()
nextInt()method. The scanner does not advance past any input.
IllegalStateException- if this scanner is closed
public boolean hasNextInt(int radix)
nextInt()method. The scanner does not advance past any input.
radix- the radix used to interpret the token as an int value
IllegalStateException- if this scanner is closed
public int nextInt()
An invocation of this method of the form
nextInt() behaves in exactly the same way as the
invocation nextInt(radix), where
radix
is the default radix of this scanner.
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public int nextInt(int radix)
InputMismatchExceptionif the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
If the next token matches the Integer regular expression defined
above then the token is converted into an int value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via
Character.digit
, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to
Integer.parseInt
with the
specified radix.
radix- the radix used to interpret the token as an int value
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public boolean hasNextLong()
nextLong()method. The scanner does not advance past any input.
IllegalStateException- if this scanner is closed
public boolean hasNextLong(int radix)
nextLong()method. The scanner does not advance past any input.
radix- the radix used to interpret the token as a long value
IllegalStateException- if this scanner is closed
public long nextLong()
An invocation of this method of the form
nextLong() behaves in exactly the same way as the
invocation nextLong(radix), where
radix
is the default radix of this scanner.
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public long nextLong(int radix)
InputMismatchExceptionif the next token cannot be translated into a valid long value as described below. If the translation is successful, the scanner advances past the input that matched.
If the next token matches the Integer regular expression defined
above then the token is converted into a long value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via
Character.digit
, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to
Long.parseLong
with the
specified radix.
radix- the radix used to interpret the token as an int value
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public boolean hasNextFloat()
nextFloat()method. The scanner does not advance past any input.
IllegalStateException- if this scanner is closed
public float nextFloat()
InputMismatchExceptionif the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input that matched.
If the next token matches the Float regular expression defined above
then the token is converted into a float value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via
Character.digit
, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to
Float.parseFloat
. If the token matches
the localized NaN or infinity strings, then either “Nan” or “Infinity”
is passed to
Float.parseFloat
as
appropriate.
InputMismatchException- if the next token does not match the Float regular expression, or is out of range
NoSuchElementException- if input is exhausted
IllegalStateException- if this scanner is closed
public boolean hasNextDouble()
nextDouble()method. The scanner does not advance past any input.
IllegalStateException- if this scanner is closed
public double nextDouble()
InputMismatchExceptionif the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
If the next token matches the Float regular expression defined above
then the token is converted into a double value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via
Character.digit
, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to
Double.parseDouble
. If the token matches
the localized NaN or infinity strings, then either “Nan” or “Infinity”
is passed to
Double.parseDouble
as
appropriate.
InputMismatchException- if the next token does not match the Float regular expression, or is out of range
NoSuchElementException- if the input is exhausted
IllegalStateException- if this scanner is closed
public boolean hasNextBigInteger()
BigIntegerin the default radix using the
nextBigInteger()method. The scanner does not advance past any input.
BigInteger
IllegalStateException- if this scanner is closed
public boolean hasNextBigInteger(int radix)
BigIntegerin the specified radix using the
nextBigInteger()method. The scanner does not advance past any input.
radix- the radix used to interpret the token as an integer
BigInteger
IllegalStateException- if this scanner is closed
public BigInteger nextBigInteger()
BigInteger.
An invocation of this method of the form
nextBigInteger() behaves in exactly the same way as the
invocation nextBigInteger(radix), where
radix
is the default radix of this scanner.
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if the input is exhausted
IllegalStateException- if this scanner is closed
public BigInteger nextBigInteger(int radix)
BigInteger.
If the next token matches the Integer regular expression defined
above then the token is converted into a BigInteger value as if
by removing all group separators, mapping non-ASCII digits into ASCII
digits via the
Character.digit
, and passing the
resulting string to the
BigInteger(String, int)
constructor with the specified radix.
radix- the radix used to interpret the token
InputMismatchException- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException- if the input is exhausted
IllegalStateException- if this scanner is closed
public boolean hasNextBigDecimal()
BigDecimalusing the
nextBigDecimal()method. The scanner does not advance past any input.
BigDecimal
IllegalStateException- if this scanner is closed
public BigDecimal nextBigDecimal()
BigDecimal.
If the next token matches the Decimal regular expression defined
above then the token is converted into a BigDecimal value as if
by removing all group separators, mapping non-ASCII digits into ASCII
digits via the
Character.digit
, and passing the
resulting string to the
BigDecimal(String)
constructor.
InputMismatchException- if the next token does not match the Decimal regular expression, or is out of range
NoSuchElementException- if the input is exhausted
IllegalStateException- if this scanner is closed
public Scanner reset()
Resetting a scanner discards all of its explicit state
information which may have been changed by invocations of
useDelimiter(java.util.regex.Pattern)
,
useLocale(java.util.Locale)
, or
useRadix(int)
.
An invocation of this method of the form scanner.reset() behaves in exactly the same way as the invocation
Scanner trong Java là gì? Có rất nhiều thảo luận về lớp đặc biệt này trong Java. Cùng CodeGym Hà Nội tìm hiểu, thảo luận về phương thức của nó và hàm tạo lớp trong Java nhé!
Nội dung
Dùng lớp Scanner trong Java
Nhập lớp Scanner xong, chúng ta phải lấy kết quả thể hiện của lớp này để đọc đầu vào từ người dùng.
Ví dụ:
Ta sẽ thực hiện một thí dụ như sau.
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Nhap mot tu bat ky: "); String chuoi_ky_tu = input.nextLine(); System.out.println(chuoi_ky_tu); input.close(); } }
Kết quả:
Nhap mot tu bat ky: xin chao xin chao
Trong ví dụ trên, câu lệnh:
Scanner input = new Scanner(System.in);
Ở đây, ta đã tạo một đối tượng của lớp Scanner có tên là
input
. Tham số
System.in
được dùng để lấy đầu vào. Tiếp theo, ta đã dùng phương thức
nextLine()
của lớp Scanner để đọc một chuỗi ký tự từ người dùng.
Từ ví dụ trên, ta cần thêm gói
java.util.Scanner
trước khi có thể dùng lớp Scanner.
import java.util.Scanner;
>> Đọc thêm: Khóa học lập trình Java
Cách thức hoạt động của Lớp Scanner
Lớp Scanner đọc toàn bộ dòng ký tự và chia thành các token. Ta có thể tạm hiểu token là các thành phần nhỏ có ý nghĩa đối với trình biên dịch trong Java.
Ví dụ: Giả sử có một chuỗi đầu vào như sau.
Xin chao moi nguoi
Trong trường hợp này, đối tượng lớp Scanner sẽ đọc toàn bộ dòng ký tự và chia thành các token: “Xin”, “chao”, “moi” và “nguoi”. Đối tượng sau đó thực hiện vòng lặp duyệt qua từng token và đọc từng token bằng các phương thức khác nhau.
Chú ý: Theo mặc định, khoảng trắng sẽ được dùng để phân chia các token.
Trên đây là khái niệm và ví dụ cơ bản về lớp Scanner trong Java. Hy vọng các bạn có thể áp dụng được vào trong chương trình của mình. Mọi người hãy tiếp tục theo dõi các bài tiếp theo và cập nhật các bài mới nhất trên CodeGym Hà Nội nhé!
Lớp Scanner trong Java
Lớp Scanner trong Java là một lớp được xác định trước giúp chúng ta lấy đầu vào từ người dùng. Lớp này có trong gói java.util và chúng ta cần nhập gói này vào bên trong chương trình Java của mình để sử dụng lớp này. Có nhiều phương thức được xác định trước trong lớp java.util.Scanner để thực hiện các hoạt động khác nhau như đọc và phân tích cú pháp các kiểu nguyên thủy khác nhau. Về cơ bản, chúng ta phải tạo đối tượng của lớp Scanner để sử dụng các phương thức này. Lớp Scanner cũng có thể phân tích cú pháp chuỗi và kiểu nguyên thủy bằng cách sử dụng biểu thức chính quy.
Lớp Scanner trong Java mở rộng lớp Object và triển khai các giao diện Cloneable và Iterator.
Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered).
Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions where XYZ is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).
Example 2:
Let us look at the code snippet to read some numbers from the console and print their mean.
Nhập lớp Scanner trong Java
Để sử dụng các phương thức và chức năng của lớp Scanner, chúng ta cần đưa lớp vào chương trình Java của mình bằng cách nhập gói java.util bằng cách sử dụng từ khóa import ở đầu mã.
Chúng ta có thể làm điều đó theo hai cách sau:
import java.util.Scanner;
//nhập lớp Scanner trong Java
import java.util.*;
//nhập tất cả các lớp của gói trong java.util
What does import java.util Scanner mean?
The
java.util.Scanner
class is one of the first components that new Java developers encounter. To use it in your code, you should import it, although another option is to explicitly reference the package in your code.
There are multiple ways to import the Java Scanner class into your code.
Java’s Scanner class makes it easy to get input from the user, which allows simple programs to quickly become interactive. And a little bit of interactivity always makes learning how to program a computer just a little bit more fun.
However, there is one minor complexity the Java Scanner class add into the software development mix.
In order to use the Java Scanner class in your code, you must either fully reference the java.util package when you call the Scanner, or you must add a Java Scanner import statement at the start of your class.
To keep your code readable and less verbose, a Java Scanner import is recommended.
When you add an import statement to your code, you are telling the Java compiler that you need access to a class that isn’t accessible by default. The
java.util.Scanner
import statement at the top of many Java classes means that somewhere in the code, the Scanner class is being used.
Java user input made easy
Learn the easiest ways to handle user input in Java, and format any console output with printf.
Java User Input
The
Scanner
class is used to get
user input, and it is found in the
java.util
package.
To use the
Scanner
class, create an object of the class and use any of the available methods found in the
Scanner
class documentation.
In our example, we will use the
nextLine()
method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner class class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input } }
If you don’t know what a package is, read our Java Packages Tutorial.
Conclusion
The Scanner in Java is a vital tool for speeding up user input processing in Java. It enables developers to create interactive apps capable of smoothly integrating user interactions because of its vast number of techniques specialized to different data kinds. Discovering the Scanner class in Java’s complexities will set you on a path to developing Java apps that are more engaging and user-focused. You will improve user experiences and optimize data aggregation within your Java endeavors as you apply your newly acquired skill in real settings, eventually influencing the development of a more complex programming environment.
If you are looking to enhance your software development skills further, we would highly recommend you to check Simplilearn’s Professional Certificate Program in Full Stack Web Development – MERN. This course, in collaboration with IIT Madras, can help you hone the right skills and make you job-ready in no time.
If you have any questions or doubts, feel free to post them in the comments section below. Our team will get back to you at the earliest.
Create a Scanner Object in Java
Once we import the package, here is how we can create
Scanner
objects.
// read input from the input stream Scanner sc1 = new Scanner(InputStream input); // read input from files Scanner sc2 = new Scanner(File file); // read input from a string Scanner sc3 = new Scanner(String str);
Here, we have created objects of the
Scanner
class that will read input from InputStream, File, and String respectively.
Hàm tạo của lớp Scanner trong Java
Lớp Scanner chứa các hàm tạo cho các mục đích cụ thể mà chúng ta có thể sử dụng trong chương trình Java của mình.
STT
Hàm tạo
Mô tả
Scanner (Nguồn tệp)
tạo đối tượng Scanner tạo ra các giá trị được quét từ tệp được chỉ định
Scanner (File source, String charsetName)
xây dựng đối tượng Scanner tạo ra các giá trị được quét từ tệp được chỉ định
Scanner (InputStream source)
tạo một đối tượng Scanner mới tạo ra các giá trị được quét từ luồng đầu vào được chỉ định.
Scanner (InputStream source, String charsetName)
tạo một Scanner mới tạo ra các giá trị được quét từ luồng đầu vào được chỉ định.
Scanner (Readable source)
tạo một Scanner mới tạo ra các giá trị được quét từ nguồn được chỉ định.
Scanner (String source)
tạo một Scanner mới tạo ra các giá trị được quét từ chuỗi được chỉ định.
Scanner (ReadableByteChannel source)
tạo một Scanner mới tạo ra các giá trị được quét từ kênh được chỉ định.
tạo một Máy quét mới tạo ra các giá trị được quét từ kênh được chỉ định.
Scanner (Path source)
tạo một Scanner mới tạo ra các giá trị được quét từ tệp được chỉ định.
10
Scanner (Path source, String charsetName)
tạo một Scanner mới tạo ra các giá trị được quét từ tệp được chỉ định
>>> Đọc thêm: Lập trình Socket trong Java – Nâng cấp kỹ năng lập trình Java của bạn
What does import java.util Scanner mean?
The
java.util.Scanner
class is one of the first components that new Java developers encounter. To use it in your code, you should import it, although another option is to explicitly reference the package in your code.
There are multiple ways to import the Java Scanner class into your code.
Java’s Scanner class makes it easy to get input from the user, which allows simple programs to quickly become interactive. And a little bit of interactivity always makes learning how to program a computer just a little bit more fun.
However, there is one minor complexity the Java Scanner class add into the software development mix.
In order to use the Java Scanner class in your code, you must either fully reference the java.util package when you call the Scanner, or you must add a Java Scanner import statement at the start of your class.
To keep your code readable and less verbose, a Java Scanner import is recommended.
When you add an import statement to your code, you are telling the Java compiler that you need access to a class that isn’t accessible by default. The
java.util.Scanner
import statement at the top of many Java classes means that somewhere in the code, the Scanner class is being used.
Java user input made easy
Learn the easiest ways to handle user input in Java, and format any console output with printf.
Kết luận
Lớp Scanner trong Java bạn có thể hiểu và tưởng tượng là một “cái máy in”, có thể nhập và xuất ra dữ liệu. Bài viết trên đã giới thiệu cho bạn về lớp Scanner trong Java, cho bạn rõ hơn định nghĩa Scanner trong Java là gì? Và các phương thức và hàm tạo của lớp Scanner. Mong rằng bạn có thể hiểu rõ hơn về Scanner trong Java qua bài viết này. Tìm hiểu thêm về Java và các ngôn ngữ lập trình khác qua các khóa học lập trình chuyển nghiệp tại CodeGym Hà Nội bạn nhé!
Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.
The Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0) method which returns a single character.
Example 2: Java Scanner nextInt()
import java.util.Scanner; class Main { public static void main(String[] args) { // creates a Scanner object Scanner input = new Scanner(System.in); System.out.println("Enter an integer: "); // reads an int value int data1 = input.nextInt(); System.out.println("Using nextInt(): " + data1); input.close(); } }
Output
Enter an integer: 22 Using nextInt(): 22
In the above example, we have used the
nextInt()
method to read an integer value.
Java Scanner Methods
The Java Scanner class also comes with several methods to create more robust input collection techniques. In addition, scanner methods can help develop stringent rules and guidelines for user input, like the type and the amount of data it can accept.
Combining the Scanner with other functions, methods, etc., makes it an even more powerful tool. For example, you can ensure that only permitted characters get validated and entered into the software database. In video game development, you can use it to build a character creation phase, where a user will enter information like their name.
nextInt(): Reads a single int value from the input. (Format: Unbroken number)
nextFloat(): Reads a single float value from the input. (Format: Up to 32 digit decimal)
nextBloolean(): Reads a single boolean value from the input. (true/false)
nextLine(): Reads a single line value from the input. (stops at \n)
next(): Reads a single word value from the input. (stops at “whitespace”)
nextByte(): Reads a single byte value from the input.
nextDouble(): Reads a single int value from the input. (Format: Up to 64 digit decimal)
nextShort(): Reads a single short value from the input. (-32,768 to 32,767)
nextLong(): Reads a single long value from the input. (-9,223,372,036,854,775,807 to 9,223,372,036,854,775,808)
Example 3
Output:
Boolean Result: false
—Tokenizes String—
Hello
This is JavaTpoint
My name is Abhishek.
Delimiter used: /
The
Scanner
class of the
java.util
package is used to read input data from different sources like input streams, files, etc. Let’s take an example.
What is a wildcard import in Java?
There are over 100 classes in the java.util package.
When you import the Java scanner with the import
java.util.*;
statement, you gain access to each class in the java.util package without adding any more import statements.
In contrast, when an explicit Java Scanner import is performed with the import
java.util.Scanner;
statement, only the Scanner class becomes available to your code. To use other classes in the java.util package, you must add explicit imports of those classes.
For the sake of simplicity, I recommend new developers use the wildcard approach wto import the Java Scanner class. It requires fewer keystrokes and reduces the opportunity to introduce compile-timer errors into your code.
package com.mcnz.example; // This example uses the wildcard import syntax import java.util.*; public class ScannerUserInput { public static void main(String[] args) { // String input with the Java Scanner System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); } }
Furthermore, if you use an IDE such as Eclipse or VS Code, an import formatter will convert wildcards imports to explicit imports when you finish development.
Senior developers find that implicit imports lead to more readable code, and also avoid possible import collisions when a class appears in two separate packages. For example, the Date class exists in both the java.util and java.sql packages, which can lead to a great deal of confusion if an application uses both packages.
Does a wildcard import hurt performance?
Some developer think doing a
java.util.*;
import might impact the performance of their code because so many classes become available to your program. However, this is not true. The wildcard import simply makes every class in a package available while you develop your app. It has no impact on the size of the application that eventually gets built.
Java Scanner Class Methods
The following are the list of Scanner methods:
SN
Modifier & Type
Method
Description
1)
void
close()
It is used to close this scanner.
2)
pattern
delimiter()
It is used to get the Pattern which the Scanner class is currently using to match delimiters.
3)
Stream
findAll()
It is used to find a stream of match results that match the provided pattern string.
4)
String
findInLine()
It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
5)
string
findWithinHorizon()
It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
6)
boolean
hasNext()
It returns true if this scanner has another token in its input.
7)
boolean
hasNextBigDecimal()
It is used to check if the next token in this scanner’s input can be interpreted as a BigDecimal using the nextBigDecimal() method or not.
8)
boolean
hasNextBigInteger()
It is used to check if the next token in this scanner’s input can be interpreted as a BigDecimal using the nextBigDecimal() method or not.
9)
boolean
hasNextBoolean()
It is used to check if the next token in this scanner’s input can be interpreted as a Boolean using the nextBoolean() method or not.
10)
boolean
hasNextByte()
It is used to check if the next token in this scanner’s input can be interpreted as a Byte using the nextBigDecimal() method or not.
11)
boolean
hasNextDouble()
It is used to check if the next token in this scanner’s input can be interpreted as a BigDecimal using the nextByte() method or not.
12)
boolean
hasNextFloat()
It is used to check if the next token in this scanner’s input can be interpreted as a Float using the nextFloat() method or not.
13)
boolean
hasNextInt()
It is used to check if the next token in this scanner’s input can be interpreted as an int using the nextInt() method or not.
14)
boolean
hasNextLine()
It is used to check if there is another line in the input of this scanner or not.
15)
boolean
hasNextLong()
It is used to check if the next token in this scanner’s input can be interpreted as a Long using the nextLong() method or not.
16)
boolean
hasNextShort()
It is used to check if the next token in this scanner’s input can be interpreted as a Short using the nextShort() method or not.
17)
IOException
ioException()
It is used to get the IOException last thrown by this Scanner’s readable.
18)
Locale
locale()
It is used to get a Locale of the Scanner class.
19)
MatchResult
match()
It is used to get the match result of the last scanning operation performed by this scanner.
20)
String
next()
It is used to get the next complete token from the scanner which is in use.
21)
BigDecimal
nextBigDecimal()
It scans the next token of the input as a BigDecimal.
22)
BigInteger
nextBigInteger()
It scans the next token of the input as a BigInteger.
23)
boolean
nextBoolean()
It scans the next token of the input into a boolean value and returns that value.
24)
byte
nextByte()
It scans the next token of the input as a byte.
25)
double
nextDouble()
It scans the next token of the input as a double.
26)
float
nextFloat()
It scans the next token of the input as a float.
27)
int
nextInt()
It scans the next token of the input as an Int.
28)
String
nextLine()
It is used to get the input string that was skipped of the Scanner object.
29)
long
nextLong()
It scans the next token of the input as a long.
30)
short
nextShort()
It scans the next token of the input as a short.
31)
int
radix()
It is used to get the default radix of the Scanner use.
32)
void
remove()
It is used when remove operation is not supported by this implementation of Iterator.
33)
Scanner
reset()
It is used to reset the Scanner which is in use.
34)
Scanner
skip()
It skips input that matches the specified pattern, ignoring delimiters
35)
Stream
tokens()
It is used to get a stream of delimiter-separated tokens from the Scanner object which is in use.
36)
String
toString()
It is used to get the string representation of Scanner using.
37)
Scanner
useDelimiter()
It is used to set the delimiting pattern of the Scanner which is in use to the specified pattern.
38)
Scanner
useLocale()
It is used to sets this scanner’s locale object to the specified locale.
39)
Scanner
useRadix()
It is used to set the default radix of the Scanner which is in use to the specified radix.
What is a wildcard import in Java?
There are over 100 classes in the java.util package.
When you import the Java scanner with the import
java.util.*;
statement, you gain access to each class in the java.util package without adding any more import statements.
In contrast, when an explicit Java Scanner import is performed with the import
java.util.Scanner;
statement, only the Scanner class becomes available to your code. To use other classes in the java.util package, you must add explicit imports of those classes.
For the sake of simplicity, I recommend new developers use the wildcard approach wto import the Java Scanner class. It requires fewer keystrokes and reduces the opportunity to introduce compile-timer errors into your code.
package com.mcnz.example; // This example uses the wildcard import syntax import java.util.*; public class ScannerUserInput { public static void main(String[] args) { // String input with the Java Scanner System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); } }
Furthermore, if you use an IDE such as Eclipse or VS Code, an import formatter will convert wildcards imports to explicit imports when you finish development.
Senior developers find that implicit imports lead to more readable code, and also avoid possible import collisions when a class appears in two separate packages. For example, the Date class exists in both the java.util and java.sql packages, which can lead to a great deal of confusion if an application uses both packages.
Does a wildcard import hurt performance?
Some developer think doing a
java.util.*;
import might impact the performance of their code because so many classes become available to your program. However, this is not true. The wildcard import simply makes every class in a package available while you develop your app. It has no impact on the size of the application that eventually gets built.
Scanner trong java là gì?
Có nhiều bạn hỏi “Scanner java là gì?” hay “Scanner trong java là gì?”
Scanner trong Java là gì?
Scanner trong Java là lớp được dùng để đọc dữ liệu đầu vào từ các nguồn khác nhau như luồng đầu vào, người dùng, tệp. Đây là lớp có trong gói java.util, và gói này cần được nhập vào bên trong chương trình java để lớp scanner được chạy. Với nhiều phương thức được xác định trước trong lớp java.util.Scanner để thực hành các hoạt động khác nhau như: đọc hay phân tách cú pháp những kiểu nguyên thủy khác nhau. Bằng cách dùng biểu thức chính quy, lớp Scanner cũng có thể phân tích cú pháp dạng chuỗi và kiểu nguyên thủy
Lớp Scanner trong Java mở rộng lớp Object và triển khai được các giao diện Cloneable và Iterator.
Why must we import the Java Scanner class?
With no added import statements to your code, your Java app has default access to all of the classes in the java.lang package. This includes classes such as:
String
System
Integer
Double
Math
Exception
Thread
However, to use any classes in packages other than java.lang in your code, an import is required.
The Scanner class is found in the java.util package, not java.lang.
Since the Scanner class is found outside of java.lang, you must either directly reference the java.util package every time you use the Scanner, or just add a single Scanner import statement to your Java file.
Input Types
In the example above, we used the
nextLine()
method, which is used to read Strings. To read other types, look at the table below:
Method
Description
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Enter name, age and salary:"); // String input String name = myObj.nextLine(); // Numerical input int age = myObj.nextInt(); double salary = myObj.nextDouble(); // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } }
Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like “InputMismatchException”).
You can read more about exceptions and how to handle errors in the Exceptions chapter.
In software development, the program will inevitably require information for the user at some point. For example, some websites may only require an age to view the content, while video games require a constant flow of user input. However, capturing user input and putting it to use is a subject that tends to be under-discussed, so let’s talk about it.
In this post, you will discover the Java class called Scanner and how to create an instance of it. You will also learn about the different methods that come with it and how they extend or specify the behavior of the scanner class. Finally, you will see some code examples from the view of developing a simple character creation phase for a hypothetical video game.
How to Import Scanner in Java
Java Scanner Methods
How to Use Scanner in Java
How to Start Scanning for User Input With Java
Without further delay, let’s jump right in.
Các phương thức của lớp Scanner để lấy đầu vào
Lớp Scanner cung cấp các phương thức khác nhau cho phép chúng ta đọc các đầu vào thuộc các kiểu khác nhau.
Phương thức
Mô tả
nextInt()
Đọc một giá trị kiểu int.
nextFloat()
Đọc một giá trị kiểu float.
nextBoolean()
Đọc một giá trị kiểu Boolean.
nextLine()
Đọc một dòng văn bản.
next()
Đọc một từ.
nextByte()
Đọc một giá trị ở dạng byte.
nextDouble()
Đọc một giá trị kiểu double.
nextShort()
Đọc một giá trị kiểu short.
nextLong()
Đọc một giá trị kiểu long.
Có thể hiểu phương thức của Scanner bằng một ví dụ thực tiễn sau:
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Nhap mot so nguyen: "); int a = input.nextInt(); System.out.println(a); input.close(); } }
Kết quả:
Nhap mot so nguyen: 4 4 hasNextXYZ ()
Trong ví dụ trên, chúng ta đã dùng phương thức nextInt() để đọc 1 giá trị là số nguyên.
Nextline trong java là gì?Hasnextline trong java là gì
Đôi lúc ta cần kiểm tra xem giá trị tiếp theo ta đọc có thuộc một loại nào không, hoặc đầu vào có EOF hay không. Tiếp theo, mình nên kiểm tra xem đầu vào của máy quét có thuộc loại mình muốn hay không? Với sự trợ giúp của các hàm hasNextXYZ () trong đó XYZ là kiểu dữ liệu mà minh muốn dùng. Phương thức trả về true (đúng) khi máy quét có mã thông báo thuộc loại đó ngược lại trả về false (sai). Với một số phương thức boolean cho mỗi mẫu dữ liệu. Để ta rà soát xem mã thông báo tiếp theo của một mẫu dữ liệu cụ thể có sẵn trong đầu vào nhất định hay không?
Ta có bảng sau:
Phương thức
Mô tả
boolean hasNextBoolean ()
kiểm tra mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu Boolean bằng phương thức nextBoolean () hay không
boolean hasNextByte ()
kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu là Byte bằng cách dùng phương thức nextByte () hay không
boolean hasNextDouble ()
kiểm tra mã thông báo tiếp theo trong máy quét này có phải đầu vào BigDecimal bằng cách dùng phương thức nextBigDecimal () hay không
boolean hasNextFloat ()
Phương pháp này kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu một Float bằng cách dùng phương thức nextFloat () hay không
boolean hasNextInt ()
kiểm tra mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu một int dùng phương thức nextInt () hay không
boolean hasNextLine ()
kiểm tra có dòng khác trong đầu vào của máy quét này hay không
boolean hasNextLong ()
kiểm tra mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu Long bằng phương thức nextLong () hay không.