Monday, December 12, 2022

10 Examples Of Scanner Class In Java

Hello guys, if you want to learn about Scanner class in Java, one of the most popular class to read input from command prompt or console then you have come to the right place. In this article, I will explain how to read input from command prompt, what is Scanner class and how you can use Scanner class to read various data types like String, int, long, boolean directly from console. You must have heard about famous nextInt(), nextDouble() methods which can read integer and double values from command prompt or console. But, before we get to the 10 best examples that will teach you everything you need to know about scanner class in Java, let me tell you a little bit more about what it really is.


10 Examples Of Scanner Class In Java

If you are at least a little bit familiar with Java, you may already know about the standard input and output methods used by Java for reading and writing data into standard devices. But Java also gives you another mechanism to read user input

This is known as the scanner class. Even though the scanner class is not very efficient, it is still one of the easiest and most popular ways to read input in Java programs.

The Scanner class can be used to scan and read the input of primitive data inputs like decimal, int, and double. It will return a tokenized input according to some delimiter pattern. For example, if you want to read the type dt, you can use the function nextdt() for reading the input.

1. Importing the Scanner

As you know, the scanner class belongs to the java.util package. So if you want to use the scanner class in your program, you need to import this package. You can use the following syntax:

import java.util.

You can also use the following syntax:

import java.util.Scanner;

2. Basic Example of Java Scanner Class

You can use the scanner to read the inputs of a lot of data types. You can pass the appropriate predefined object to the scanner object if you want to read input from a file or a channel. 

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();             
            }  
}  




3. Constructors And Methods

The scanner class is made up of various overloaded constructors that can accommodate a lot of input methods like file input, path, and System.in. 
  • Scanner(InputStream source) will construct a new scanner that will scan a new InputStream and produce the necessary values. 
  • Scanner(File Source) constructs a new scanner that will scan a specified file and produce the necessary values. 
  • Scanner(String sources will construct a new scanner that will scan a specific string and produce the values. 
  • Scanner(Path source, string charsetName) constructs a new scanner that scans the specified file and produces the values,
  • Scanner(ReadableByteChannel source) constructs a new scanner that scans the specified channel and produces the values.

4. Scanner Prototypes

  • Boolean hasNext() returns true if there is another token in Scanner’s input.
  • Boolean hasNextBigInteger() checks if the next token in the Scanner input is of bigInteger type.
  • Boolean hasNextByte() checks if the next token in the Scanner input is of type Byte.
  • Boolean hasNextFloat() checks if the next token in the Scanner input is of float type.
  • Boolean hasNextLine() checks if the next token in the Scanner input is another line.
  • Boolean hasNextShort() checks if the next token in the Scanner input is of short type.
  • BigDecimal nextBigDecimal() scans the input for next BigDecimal token.
  • Boolean nextBoolean() scans the input for the next Boolean token.
  • Double nextDouble() scans the input for the next Double token.
  • Int nextInt() scans the input for the next integer token.
  • Long nextLong() scans the input for the next Long integer token.
  • Scanner reset() will reset the Scanner currently in use.



5. Using The Scanner

The implementation given below will show you how to use the scanner class to read input from System.in. We will use a predefined System.in object for creating a scanner object. 
See the following program for more information:

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);
     }
}





6. Scanner String

Using the scanner, you can also read input from strings. You can use regular expressions inside the string input. In the following program, the scanner uses a string as an input. See the example to gain a better understanding:

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(); 
     }
}

7. Closing The Scanner

It is pretty easy to close the scanner. You can use the Close() method to close the scanner. It is good to explicitly close the scanner using the Close() method when you are done using it. 


8. 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();
  }
}

This program will give you the following output:

Enter your name: Kelvin
My name is Kelvin

8. Creating A Scanner Object

// 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);




9. Java Scanner With 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();
  }
}

You will get the following output:

Enter an integer:
22
Using nextInt(): 22


10. Java Scanner Using 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();
  }
}

This program will give you the following output:

Enter Double value: 33.33
Using nextDouble(): 33.33


That's all about how to use Scanner class in Java. We have seen different example of Scanner class for reading integer values using nextInt(), double values using nextDouble() as well as many other example of reading user input from Console. If you liked this list of 10 examples of scanner class in Java, feel free to share it with your friends and family.


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.