banner



How To Create A Scanner Class In Java

In this tutorial, we will discuss How to Import and Use the Scanner Class of Java along with its Various Methods, Scanner API, and Examples:

We have already seen the standard Input-Output methods used by Java for reading/writing data to the standard I/O devices.

Java provides yet another mechanism to read user input. This is the Scanner class. Though not very efficient, Scanner class is the easiest and preferred way to read input in Java programs.

=> Check ALL Java Tutorials Here.

Java Scanner Class

What You Will Learn:

  • Java Scanner Class: An In-Depth Look
    • Import Scanner
    • Java Scanner Class
    • Scanner API (Constructors & Methods)
    • How To Use The Scanner In Java?
    • Scanner String
    • Close Scanner
    • Frequently Asked Questions
  • Conclusion
    • Recommended Reading

Java Scanner Class: An In-Depth Look

Scanner class is mostly used to scan the input and read the input of primitive (built-in) data types like int, decimal, double, etc. Scanner class basically returns the tokenized input based on some delimiter pattern. Thus, in general, if you want to read the type dt, then you could use the function nextdt () to read the input.

A Scanner class implements Iterator (string), Closeable, and AutoCloseable interfaces.

Let's explore the details of this Scanner class now.

Import Scanner

Scanner class belongs to the "java.util" package. Hence to use the Scanner class in your program, you need to import this package as follows.

import java.util.*

OR

import java.util.Scanner;

Either of the above statements will import the Scanner class and its functionality in your program.

Java Scanner Class

Once the Scanner class is imported into the Java program, you can use it to read the input of various data types. Depending on whether you want to read the input from standard input or file or channel, you can pass the appropriate predefined object to the Scanner object.

Given below is a basic example of Scanner class usage.

import java.util.*;   public class Main  {   	public static void main(String args[]) 	{             	        Scanner in = new Scanner (System.in);             	        System.out.print ("Enter a String: ");             	        String mystr = in.nextLine();           	        System.out.println("The String you entered is: " + mystr);                       	        in.close();                         	}   }        

Output:

Scanner class Output

In the above program, we have provided the "System.in" (standard Input) as the object while creating a Scanner class object. Then we read a string input from the standard input.

Scanner API (Constructors & Methods)

In this section, we will explore the Scanner class API in detail. Scanner class contains various overloaded constructors to accommodate various input methods like System.in, file input, path, etc.

The following table gives the prototype and description of each of the Scanner class constructors.

Just like constructors, the Scanner class also provides numerous methods that are used to scan and read the input. It provides various Boolean methods that allow you to check if the next token in the input is a token of a particular data type.

Note that for each constructor, you can either provide only one argument with the predefined input object or two arguments consisting of predefined input object and character set. In the case of one argument, the default character set is assumed.

There are also methods to retrieve tokens of each data type.

Other methods include those to set locale, radix, match patterns, close Scanner, etc.

The following table gives the prototype and description of each of the basic Scanner methods.

No Prototype Description
1 Boolean hasNext() Returns true if there is another token in Scanner's input
2 Boolean hasNextBigDecimal() Checks if the next token in the Scanner input is of bigDecimal type.
3 Boolean hasNextBigInteger() Checks if the next token in the Scanner input is of bigInteger type
4 Boolean hasNextBoolean() Checks if the next token in the Scanner input is of Boolean type
5 Boolean hasNextByte() Checks if the next token in the Scanner input is of type Byte
6 Boolean hasNextDouble() Checks if the next token in the Scanner input is of double type
7 Boolean hasNextFloat() Checks if the next token in the Scanner input is of float type
8 Boolean hasNextInt() Checks if the next token in the Scanner input is of integer type
9 Boolean hasNextLine() Checks if the next token in the Scanner input is another line
10 Boolean hasNextLong() Checks if the next token in the Scanner input is of long type
11 Boolean hasNextShort() Checks if the next token in the Scanner input is of short type
12 String next() Scans the input for next complete token
13 BigDecimal nextBigDecimal() Scans the input for next BigDecimal token
14 BigInteger nextBigInteger() Scans the input for next BigInteger token
15 Boolean nextBoolean() Scans the input for next Boolean token
16 Byte nextByte() Scans the input for next Byte token
17 Double nextDouble() Scans the input for next Double token
18 Float nextFloat() Scans the input for next float token
19 Int nextInt() Scans the input for next integer token
20 String nextLine() Get the input string skipped from Scanner object
21 Long nextLong() Scans the input for next Long integer token
22 Short nextShort() Scans the input for next Short integer token
23 Scanner reset() Reset the Scanner currently in use
24 Scanner skip() Ignore delimiters and skip the input that matches the given pattern
25 Scanner useDelimiter() Set the delimiting pattern to the specified pattern
26 Scanner useLocale() Set the Scanners locale object with the given locale
27 Scanner useRadix() Set the specified radix as the default radix for Scanner
28 Int radix() Returns default radix of the current Scanner
29 void remove() Can be used when Iterator does not support remove operation
30 Stream tokens() Returns a stream of delimiter separated tokens from the current Scanner
31 String toString() The return string representation of given Scanner currently in use
32 IOException ioException() Returns the IOException last thrown by readable of Scanner object
33 Stream findALL() Returns the stream of match results that match the given pattern
34 String findInLine() Find the next occurrence of the pattern from the given string; ignores delimiters
35 String findWithinHorizon() Find the next occurrence of the pattern from the given string; ignores delimiters
36 Pattern delimiter() Returns the pattern used by the current Scanner
37 Void close() Closes the Scanner
38 MatchResult match() Returns the matching result of last scanning operation
39 Locale locale() Return locale of the current Scanner

Check here to know more about the Scanner Methods.

How To Use The Scanner In Java?

Now that you have seen the various constructors and methods provided by Scanner class, let's now implement some of the examples to demonstrate how to use the Scanner class in Java.

The following implementation shows the usage of Scanner class to read input from System.in i.e. the standard input.

Here we use a predefined System.in object to create a Scanner object. The user is then prompted to enter the name, class, and percentage. All these details are read using the Scanner class object.

Note the methods used by Scanner objects to read different types of input. As the name is a string, the Scanner object uses the next () method. For class input, it uses nextInt () while for percentage it uses nextFloat ().

In this manner, you can easily segregate the input while reading.

The output of the program shows the input being entered and the information displayed.

import java.util.*;  public class Main{      public static void main(String []args){         String name;         int myclass;         float percentage;                  //creating object of Scanner class         Scanner input = new Scanner(System.in);                  System.out.print("Enter your name: ");         name = input.next();         System.out.print("Enter your class: ");         myclass = input.nextInt();         System.out.print("Enter your percentage: ");         percentage = input.nextFloat();                 input.close();         System.out.println("Name: " + name + ", Class: "+ myclass + ", Percentage: "+ percentage);      } }        

Output:

Using Scanner class Output

Scanner String

As already mentioned, you can use various predefined objects while creating a Scanner object. This means you can either read the input from standard input, files, and various I/O channels or from strings as well.

When a string input is used, you can also use regular expressions inside it.

The following examples show the program wherein Scanner uses a string as an input. This input is then scanned and tokens separated by reading each token.

The tokens read are then displayed in the output.

import java.util.*;  public class Main{      public static void main(String []args){                   System.out.println ("The subjects are as follows :");         String input = "1 Maths 2 English 3 Science 4 Hindi";         Scanner s = new Scanner(input);         System.out.print(s.nextInt()+". ");         System.out.println(s.next());         System.out.print(s.nextInt()+". ");         System.out.println(s.next());         System.out.print(s.nextInt()+". ");         System.out.println(s.next());         System.out.print(s.nextInt()+". ");         System.out.println(s.next());         s.close();       } }        

Output:

Scanner string output

Close Scanner

Java Scanner class uses the "Close ()" method to close the Scanner. The Scanner class also internally implements a Closeable interface and hence if the Scanner is not already closed, the underlying Readable interface invokes its close method.

It is a good programming practice to explicitly close the Scanner using the Close () method once you are done using it.

Note: If the Scanner object is closed and an attempt is made to search, it results in "IllegalStateException".

Frequently Asked Questions

Q #1) What is the Scanner class in Java?

Answer: The Scanner class is a part of the "java.util" package of Java and is used to read input of different primitive data types like int, float, strings, etc.

Q #2) What is the difference between the next () and nextLine () methods of the Scanner class?

Answer: The method next () reads input till space and places the cursor on the same line after reading input. The method nextLine () however reads the entire line of input till the end of line including the spaces.

Q #3) What is hasNext () in Java?

Answer: The method hasNext () is one of the Java Scanner methods. This method returns true if the Scanner has another token in the input.

Q #4) Do you need to close a Scanner class?

Answer: It is better but not mandatory to close the Scanner class as if it is not closed, the underlying Readable interface of the Scanner class does the job for you. The compiler might flash some warning though if it is not closed.

So as a good programming practice, always close the Scanner.

Q #5) What is the purpose of "system.in" in the Scanner class?

Answer: By using "System.in" in the Scanner class, you are allowing the Scanner to read the keyboard connected to standard input data.

Conclusion

In this tutorial, we have seen the Scanner class and all its details including the API and implementation. Scanner class is used to read input data from a variety of mediums like standard input, files, IO channels, strings with/without regular expressions, etc.

Although Scanner is not a very efficient way to read input, it is one of the easiest ways. The Scanner allows you to read the input of various primitive data types like int, float, strings, etc. When you use strings as an input object for Scanner class, you can also use regular expressions with it.

The Scanner class also allows you to read input by matching some pattern or delimiter.

To conclude, using Scanner class in Java remains the easiest and preferred way to read input.

=> Check Out The Perfect Java Training Guide Here.

How To Create A Scanner Class In Java

Source: https://www.softwaretestinghelp.com/java-scanner-class/

Posted by: shustermuder1970.blogspot.com

0 Response to "How To Create A Scanner Class In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel