Skip to content

Java scanner class| import | nextline, nextint, exception and examples

  • by

Java Scanner class is found in java.util package. The Scanner class is used to getting the input of the primitive data types like Strings, int, double, etc. It breaks the input using a pattern (regex), where the default regular expressions match is whitespace. This is the easiest way to get input in the java program.

Java scanner class, import nextline, nextint, exception and examples

In this tutorial you will learn how to import a Scanner class in java, What is the use, How to use it, important methods, and many examples.

Java Scanner Syntax

A very easy syntax of Scanner class, after import java.util package create a scanner object. Then use any method.

Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();

How to import Scanner Java

Java Import scanner class at the starting of the program inside the java file.

import java.util.Scanner;  // Import the Scanner class

Java Scanner Example

Let’s See the simple Java scanner string reader. Where the input type is string read from a console.

import java.util.Scanner;
 
public class Hello {
 
        public static void main(String[] args) {
            // Creating a Scanner object
            Scanner scanObj = new Scanner(System.in);
            System.out.println("Enter your name");
 
            // Read user input from console
            String input = scanObj.nextLine();
            System.out.println("You Entered: " + input);  // print user input
    }
}

Output: GIF with code structure. To use a scanner class in java, you have to import – import java.util package or import java.util.Scanner

Java Scanner Example output

Input Types in the scanner

Above example was used Java scanner nextLine() methods, which is using for get string input.

But Java scanner class supports all primitive type inputs. Read the below list supported input list data type with scanner methods. These are also called Input types in the scanner class.

Data TypeMethodDescription
booleannextBoolean()Read boolean value and returns that value.
bytenextByte()Read the input as a byte.
doublenextDouble()Read input as a double.
floatnextFloat()Read the input as a float.
intnextInt()Read the input as an int.
StringnextLine()Reads a String value from the user.
longnextLong()Read the input as a long.
shortnextShort()Read input as a short.

Example of different input types methods in Scanner class

Let’s see one by one method of Scanner class examples. We are not covering all types of methods, most are the same you can do it yourself. Every example has code lines only other parts like importing and mani methods are the same above example.

Scanner nextInt

A Method is used for reading next input as a int date type.

Scanner scanObj = new Scanner(System.in);
        System.out.println("Enter number");
        int input = scanObj.nextInt();
        System.out.println(" " + input);

Scanner nextLine

Java Scanner nextLine method used for reading string input type.

Scanner myObj = new Scanner(System.in); 
        System.out.println("Enter username");

        String userName = myObj.nextLine();  
        System.out.println("Username is: " + userName);

Java scanner nextDouble

A nextDouble method is used for racing Double type data in java. Even you enter the int value in the console it will convert to double value.

Scanner myObj = new Scanner(System.in);
        System.out.println("Enter a double value");

        double value = myObj.nextDouble();
        System.out.println("value is: " + value);

Output: Enter a double value
0
value is: 0.0

Java scanner nextbyte

byte value = myObj.nextByte();

Scanner Class Exception

A scanner nextInt method will throw an error if you enter the string in a console. See the below example.

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {

        Scanner myObj = new Scanner(System.in);
        System.out.println("Enter number only ");

        int value = myObj.nextInt();
        System.out.println("value is: " + value);
    }
}


Note: Using a try-catch block can prevent – java scanner exception.

Output: See below GIF when you enter the number is fine but if string, it will throw an error – “java.util.InputMismatchException

java Scanner Class Exception error

Other Important method and examples

A hasNext() and next() methods are useful, see examples.

hasNext() Method

The Scanner hasnext method Returns true if this scanner has another token in its input. Using this method you can stop a loop or any condition statement in the program.

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        String s = "Hello World !";


        Scanner scanner = new Scanner(s);
        System.out.println("" + scanner.hasNext());


        System.out.println("" + scanner.nextLine());

        System.out.println("" + scanner.hasNext());

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

Output:

next() Method

The Scanner next method finds and returns the next complete token from this scanner. A complete token is preceded and followed by the input that matches the delimiter pattern. 

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        String s = "Hello World !";


        Scanner scanner = new Scanner(s);
        System.out.println("" + scanner.next());
        System.out.println("" + scanner.next());

        scanner.close();
    }
}


Output: Hello
World

How to Get Scanner next char?

Answer: Using Scanner.next() method you can take first or any character from the string.

Scanner scanner = new Scanner(s);
        char c = scanner.next().charAt(0);
        System.out.println(c);

How to Reading a .txt file using Scanner class in Java?

Answer: Java scanner file

import java.io.File;
import java.util.Scanner;

public class Hello {

    public static void main(String[] args) throws Exception {
        File file=new File("test.txt");
        Scanner sc=new Scanner(file);
        while(sc.hasNextLine()){
            System.out.println(sc.nextLine());
        }
    }
}

This class introduced since Java version 1.6, so it’s most methods worked on the latest and old java version 8 etc. Do cooment if you have any doubt and suggestions.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All  Java scanner class is in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.

Leave a Reply

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