Java

Java Scanner Class with Examples using NetBeans

Java Scanner Class

Java Scanner Class with Programming Examples using NetBeans- In Java programming, there are several classes that we can use to take input from the user, namely Scanner, BufferedReader, and JOptionPane, these three classes have the same function, but in JOptionPane, this class has a visual display or GUI. An application project certainly requires input data from the user to be processed into output, in Java we can create a program that allows the user to input data in a variable and print the results on the monitor screen.


In this tutorial, we will learn Java Scanner and its methods with the help of examples using netbeans.

The PrintWriter class of the java.io package can be used to write output data in a normally readable form (text).

The Scanner class of the java.util package is used to read input data from different sources such as input streams, users, files, etc. Let’s take an example.

To use a java Scanner class, we need to create an object from the java Scanner class, the class is in the package java.util.*, so we need to import the package first, after the package and object have been created, then we need a variable to hold the value input from users. We will make a simple program using a scanner, in the program the user is asked to input something, and the results will be printed using System.out.println() , try to look at the following example program.



Example 1: Using a java scanner class to read a line of text

package com.mycompany.javabasics;
import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {
        
public  static  void  main ( String[] args )  {

        //Create Scanner object  
        Scanner GetInput =  new  Scanner(System.in );

        System.out.println ( "Enter name: " );

        // get the input from keyboard
        String name = GetInput.nextLine();

        //Display the data on the screen
        System.out.println ( "My name is "  + name);
        

        // Closes the scanner
        GetInput.close();
    }
  
}

output:

Java Scanner Class

In the above example, notice the following line

Scanner GetInput =  new  Scanner(System. in );

Here, we create a Scanner object called input.

The System.in parameter is used to get input from standard input. Like getting input from the keyboard.

To store String data, we can use the next() or  nextLine() method of the java Scanner class, in addition to the String data type, there are several other methods that you can use of the java Scanner class, including:

  • nextInt – Accepts integer/Integer input
  • nextBoolean – Accepts Boolean input (true/false)
  • nextFloat – Accepts fractional input/Float
  • nextDouble – Accepts fractional/Double input
  • nextByte – Receives an integer/Byte
  • nextLong – Receives an integer/Long
  • nextShort – Accepts an integer/Short


Example 2: how to get number data type Integer using java scanner class

package com.mycompany.javabasics;
import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {
        
    public static void main(String[] args){
        Scanner InputData = new Scanner(System.in);
        int num1, num2, Result;
        System.out.println("Enter First Number: ");
        num1 = InputData.nextInt();
        System.out.println("Enter Second Number: ");
        num2 = InputData.nextInt();
        Result = num1 + num2;
        System.out.println("The Result is: "+Result);
    }
    
}

output:

Java Scanner Class

Now that you know something about java Scanner class, let’s explore it a little more.

Import the java scanner class

As you can see from the above examples, we need to import the java.util.Scanner package before we can use the Scanner class.

import  java .util .Scanner ;


Creating Scanner Objects in Java

As mentioned above, once the package is imported, the Scanner object can be created.

//Read input from input stream

Scanner Obj1 =  new  Scanner(InputStream input);

//Read input from file

Scanner Obj2 =  new  Scanner(File file);

//Read input from string

Scanner Obj3 =  new  Scanner( String  str);

Here we have created objects of the Scanner class that will read input from InputStream, File, and String respectively.

Java scanner class input methods

The java Scanner class provides various methods that allow us to read out different types of input.

Method Description
nextInt() read int value from the user
nextFloat() read float value from the user
nextBoolean() read the boolean value from the user
nextLine() Read a line of text from the user
next() Read a word from the user
nextByte() Read byte value from the user
nextDouble() read the double value from the user
nextShort() read the short value from the user
nextLong() read the long value from the user


Example 3: nextInt() Method of the Java Scanner Class

The nextInt() method is used to get the integer values from the user. So in the below example,  I am using the nextInt() method in programming.

package com.mycompany.javabasics;

import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {

        //Create a scanner object 
        Scanner inputData = new Scanner(System.in);
        System.out.println("Enter an integer: ");

        //Read an int value 
        int data = inputData.nextInt();

        System.out.println("nextInt() Data is: " + data);

        inputData.close();
    }

}

output:

Java Scanner Class



Example 4: How to use nextDouble() method of the Java Scanner Class

The nextDouble() method is used the get the floating-point values from the user. So in the below example,  I am using the nextDouble() method in programming.

package com.mycompany.javabasics;

import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {

      //Create a Scanner object 
      Scanner inputData =  new  Scanner(System. in );
      System.out .println( "Enter double Value: " );

      //Read double value 
      double  data  = inputData.nextDouble();
      System.out.println ( "nextDouble() data is: "  +  data );

      inputData.close();
   }


} 

output:

Java Scanner Class

Example 5: next() method of the Java Scanner Class

The next() method is used to get a String from the user. in the below example,  I am using the next() method in programming.

package com.mycompany.javabasics;

import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {

        //Create a Scanner object 
        Scanner inpuData = new Scanner(System.in);
        System.out.println("Enter your name: ");

        //Read the whole word 
        String Data = inpuData.next();
        System.out.println("String Data is: " + Data);

        inpuData.close();
    }

} 

output:

Java Scanner Class

Here, we provide the full string. However, the next() method only reads the string.

This is because the next() method reads the input up to a space character. As soon as a space is encountered, it returns the string (excluding spaces). As you can see in the below image only Programming is displayed.

Java Scanner Class


Example 6: nextLine() method of the Java Scanner Class

package com.mycompany.javabasics;

import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {

        //Create a Scanner object 
        Scanner inputData = new Scanner(System.in);
        System.out.println("Enter your Data: ");

        //Read the entire line 
        String Data = inputData.nextLine();
        System.out.println("The Data is: " + Data);

        inputData.close();
    }

} 

output:

Java Scanner Class

In the first example, we used the nextLine() method to read the string from the user.

Unlike next() method, the nextLine() method reads the entire input line including spaces. Terminates when the method encounters the next line character \n.

Java Scanners BigInteger and BigDecimal

The Java scanner can also be used to read big integers and big decimal numbers.

  • nextBigInteger() – reads a big integer value from the user
  • nextBigDecimal() – reads the big decimal value from the user


Example 7: Reading BigInteger and BigDecimal numbers using Java Scanner

In the above example, we use the java.math.BigInteger and java.math.BigDecimal packages to read BigInteger and BigDecimal respectively.

package com.mycompany.javabasics;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {

        //Create a Scanner object 
        Scanner inputData = new Scanner(System.in);
        System.out.println("Enter a large integer Value: ");

        //Read big integer 
        BigInteger data1 = inputData.nextBigInteger();
        System.out.println("The large integer Value is: " + data1);

        System.out.println("Enter a big decimal Value: ");

        //Read big decimal 
        BigDecimal data2 = inputData.nextBigDecimal();
        System.out.println("The Big Decimal Value is: " + data2);

        inputData.close();
    }

} 

output:

Java Scanner Class

In the above example, we use the java.math.BigInteger and java.math.BigDecimal packages to read BigInteger and BigDecimal respectively.


Example 8: how to create Static Login program using Java Scanner Class:

package com.mycompany.javabasics;

import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {

        //Create Scanner object  
        Scanner GetInput = new Scanner(System.in);

        System.out.println("Enter Username: ");

        // get the input from keyboard
        String username = GetInput.nextLine();
        System.out.println("Enter Password: ");
        String password = GetInput.nextLine();

        if (username.equals("fawadkhan") && password.equals("khan")) {
            //Display the data on the screen
            System.out.println("Welcome To Programming Digest");
        } else {
            System.out.println("Wrong Credentials");
        }

        // Closes the scanner
        GetInput.close();
    }

}

Output:

When you enter the wrong username or password it will show the following output

Java Scanner Class

And when you enter the correct username and password, then it will show the following output

Java Scanner Class

Example 9: How to create an array in java by taking input from the console:

package com.mycompany.javabasics;

import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {
        Scanner inputData = new Scanner(System.in);
        System.out.println("enter the size of the array");
        int size = inputData.nextInt();
        int[] array = new int[size];
        for (int i = 0; i < size; i++) {
            System.out.println("enter the elements:");
            array[i] = inputData.nextInt();
        }
        inputData.close();
        System.out.println("you entered the following elements");
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

}

Output:

Java Scanner Class



Example 10: How to use java scanner Class in switch case statement:

package com.mycompany.javabasics;

import java.util.Scanner;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {
        Scanner inputData = new Scanner(System.in);
        System.out.println("Language Menu");
        System.out.println();
        System.out.println("Press 1 for Java");
        System.out.println("Press 2 for C++");
        System.out.println("Press 3 for Python");
        System.out.println("Press 4 for PHP");
        System.out.println();
        System.out.println("Enter your Choice:");
        int language = inputData.nextInt();
        switch (language) {
            case 1:
                System.out.println("you select the Java language");
                break;
            case 2:
                System.out.println("you select the C++ language");
                break;
            case 3:
                System.out.println("you select the Python language");
                break;
            case 4:
                System.out.println("you select the PHP language");
                break;
            default:
                System.out.println("Please Select the correct language");
                break;
        }

    }

}

Output:

Java Scanner Class

Java Scanner class Vs java BufferedReader class

In this section, we will use the BufferedReader class, this class is in the java.io package , this class is used to get input from the user, almost the same as Scanner, the only difference is the way of writing the syntax.

To use this class, we must first import the following packages:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.IOException;

To make it easier, you can write it like this:

import java.io.*; // this is used to import all  classes and packages

In the following example, there we create an object of the BufferedReader class, to get input from the user,  and then I used the readLine() method to read the data, and don’t forget to add a try-catch just in case something goes wrong during the input process.


Example 11: how to use BufferedReader class in java to get input from the user:

package com.mycompany.javabasics;

import java.io.*;

/**
 *
 * @author Fawadkhan
 */
public class JavaScannerClassExamples {

    public static void main(String[] args) {
        //Creating an object of the BufferedReader class
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String Data; //variable to store data
        try {
            System.out.println("Enter your Data: ");
            Data = input.readLine();//Get input string from user
            System.out.println();
            System.out.println("Your Data is: " + Data); // display output on the screen
        } catch (IOException ex) {
            // If there is an error while inputting data
            System.out.println("An Error Occurred on Input");
        }
    }

}

output:

Java Scanner Class

 

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button