Java Scanner Class
In Java, Scanner is a class that is used for getting the input of strings and different primitive types such as int, double, etc. The scanner class is found in the package java. It extends the class Object and implements the interfaces Closeable and Iterator. Inputs are broken into classes with the help of a whitespace delimiter. Declaration, syntax, working, and several other aspects of the Scanner class in Java will be discussed in the following sections.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Java Scanner Class Declaration
Java Scanner class is declared as shown below.
public final class Scanner extends Object implements Iterator<String>
Syntax:
Scanner class can be used in the below syntax in Java programs.
Scanner sc = new Scanner(System.in);
Here, sc is the scanner object and System.in tells Java that the input will be this.
How Does Java Scanner Class Work?
Now, let us see how the Scanner class works.
- Import the class java.util.Scanner or the whole package java.util.
import java.util.*; import java.util.Scanner;
- Create scanner object as shown in the syntax.
Scanner s = new Scanner(System.in);
- Declare a type int, char or string.
int n = sc.nextInt();
- Perform the operations on the input based on the requirement.
Constructors
The scanner class in Java has different constructors. They are:
- Scanner(File src): A new scanner will be constructed that generates value from the mentioned file.
- Scanner(File src, String charsetName): A new scanner will be constructed that generates value scanned from the mentioned file.
- Scanner(InputStream src): A new scanner will be constructed that generates value from the mentioned input stream.
- Scanner(InputStream src, String charsetName): A new scanner will be constructed that generates value from the mentioned input stream.
- Scanner(Path src): A new scanner will be constructed that generates value from the mentioned file.
- Scanner(Path src, String charsetName): A new scanner will be constructed that generates value from the mentioned file.
- Scanner(Readable src): A new scanner will be constructed that generates value from the mentioned source.
- Scanner(ReadableByteChannel src): A new scanner will be constructed that generates value from the mentioned channel.
- Scanner(ReadableByteChannel src, String charsetName): A new scanner will be constructed that generates value from the mentioned channel.
- Scanner(String src): A new scanner will be constructed that generates value from the mentioned string.
Methods of Java Scanner Class
Following are the methods that perform different functionalities.
- close(): Scanner gets closed on calling this method.
- findInLine(Pattern p): Next occurrence of the mentioned pattern p will be attempted to find out, ignoring the delimiters.
- findInLine(String p): The next occurrence of the pattern that is made from the string will be attempted to find out, ignoring the delimiters.
- delimiter(): Pattern that is currently used by the scanner to match delimiters will be returned.
- findInLine(String p): The next occurrence of the pattern that is made from the string will be attempted to find out, ignoring the delimiters.
- findWithinHorizon(Pattern p, int horizon): Tries to identify the mentioned pattern’s next occurrence.
- hasNext(): If the scanner has another token in the input, true will be returned.
- findWithinHorizon(String p, int horizon): Tries to identify the next occurrence of the mentioned pattern made from the string p, ignoring delimiters.
- hasNext(Pattern p): If the next token matches the mentioned pattern p, true will be returned.
- hasNext(String p): If the next token matches the mentioned pattern p made from the string p, true will be returned.
- next(Pattern p): Next token will be returned, which matches the mentioned pattern p.
- next(String p): Next token will be returned, which matches the mentioned pattern p made from the string p.
- nextBigDecimal(): Input’s next token will be scanned as a BigDecimal.
- nextBigInteger(): Input’s next token will be scanned as a BigInteger.
- nextBigInteger(int rad): Input’s next token will be scanned as a BigInteger.
- nextBoolean(): Input’s next token will be scanned as a Boolean, and it will be returned.
- nextByte(): Input’s next token will be scanned as a byte.
- nextByte(int rad): Input’s next token will be scanned as a byte.
- nextDouble(): Input’s next token will be scanned as a double.
- nextFloat(): Input’s next token will be scanned as a float.
- nextInt(): Input’s next token will be scanned as an integer.
- nextInt(int rad): Input’s next token will be scanned as an integer.
- nextLong(int rad): Input’s next token will be scanned as a long.
- nextLong(): Input’s next token will be scanned as a long.
- nextShort(int rad): Input’s next token will be scanned as a short.
- nextShort(): Input’s next token will be scanned as a short.
- radix(): The default radix of the scanner will be returned.
- useDelimiter(Pattern p): Delimiting pattern of the scanner will be set to the mentioned pattern.
- useDelimiter(String p): Delimiting pattern of the scanner will be set to the mentioned pattern made from the string p.
- useRadix(int rad): The scanner’s default radix will be set to the mentioned radix.
- useLocale(Locale loc): The locale of the scanner will be set to the mentioned locale.
Examples of Java Scanner Class
Now, let us see some sample programs of the Scanner class in Java.
Example #1
Code:
import java.util.Scanner; class ScannerExample { public static void main(String[] args) { //create object of scanner Scanner sc = new Scanner(System.in); System.out.println("Enter the username"); String obj = sc.nextLine(); System.out.println("The name you entered is: " + obj); } }
Output:
On executing the program, the user will be asked to enter a name. As the input is a string, the nextLine() method will be used. Once it is entered, a line will be printed displaying the name user given as input.
Example #2
Code:
import java.util.Scanner; class ScannerExample { public static void main(String[] args) { //create object of scanner Scanner sc = new Scanner(System.in); System.out.println("Enter age"); int obj = sc.nextInt(); System.out.println("The age you entered is: " + obj); } }
Output:
On executing the program, the user will be asked to enter the age. As the input is a number, the nextInt() method will be used. Once it is entered, a line will be printed displaying the age user given as input.
The above is the detailed content of Java Scanner Class. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
