Easy Tutorial
❮ Java String Startswith Java String Contains ❯

Java Scanner Class

java.util.Scanner is a new feature in Java 5, and we can use the Scanner class to get user input.

Below is the basic syntax for creating a Scanner object:

Scanner s = new Scanner(System.in);

Next, we demonstrate the simplest data input and retrieve the input string using the next() and nextLine() methods of the Scanner class. Typically, we need to use hasNext and hasNextLine to check if there is any input data before reading:

Using the next Method:

ScannerDemo.java File Code:

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // Receive data from the keyboard

        // Receive string using next
        System.out.println("Receiving with next:");
        // Check if there is more input
        if (scan.hasNext()) {
            String str1 = scan.next();
            System.out.println("Input data: " + str1);
        }
        scan.close();
    }
}

Executing the above program outputs:

$ javac ScannerDemo.java
$ java ScannerDemo
Receiving with next:
tutorialpro.org
Input data: tutorialpro

Notice that the "com" string is not output. Next, let's look at nextLine.

Using the nextLine Method:

ScannerDemo.java File Code:

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // Receive data from the keyboard

        // Receive string using nextLine
        System.out.println("Receiving with nextLine:");
        // Check if there is more input
        if (scan.hasNextLine()) {
            String str2 = scan.nextLine();
            System.out.println("Input data: " + str2);
        }
        scan.close();
    }
}

Executing the above program outputs:

$ javac ScannerDemo.java
$ java ScannerDemo
Receiving with nextLine:
tutorialpro.org
Input data: tutorialpro.org

Notice that the "com" string is output.

Differences Between next() and nextLine()

next():

nextLine():

To input data of type int or float, the Scanner class also supports this. It is advisable to use hasNextXxx() methods for validation before using nextXxx() to read:

ScannerDemo.java File Code:

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // Receive data from the keyboard
        int i = 0;
        float f = 0.0f;
        System.out.print("Enter an integer: ");
        if (scan.hasNextInt()) {
            i = scan.nextInt();
            System.out.println("Data: " + i);
        }
        System.out.print("Enter a float: ");
        if (scan.hasNextFloat()) {
            f = scan.nextFloat();
            System.out.println("Data: " + f);
        }
        scan.close();
    }
}
if (scan.hasNextInt()) {
    // Check if the input is an integer
    i = scan.nextInt();
    // Receive the integer
    System.out.println("Integer data: " + i);
} else {
    // Error message for incorrect input
    System.out.println("Input is not an integer!");
}
System.out.print("Enter a decimal: ");
if (scan.hasNextFloat()) {
    // Check if the input is a decimal
    f = scan.nextFloat();
    // Receive the decimal
    System.out.println("Decimal data: " + f);
} else {
    // Error message for incorrect input
    System.out.println("Input is not a decimal!");
}
scan.close();

Execution of the above program results in:

$ javac ScannerDemo.java
$ java ScannerDemo
Enter an integer: 12
Integer data: 12
Enter a decimal: 1.2
Decimal data: 1.2

The following example allows us to input multiple numbers and calculates their sum and average. Enter a non-numeric value to end the input and display the results:

ScannerDemo.java file code:

import java.util.Scanner;

class tutorialproTest {
    public static void main(String[] args) {
        System.out.println("Please enter numbers:");
        Scanner scan = new Scanner(System.in);

        double sum = 0;
        int m = 0;

        while (scan.hasNextDouble()) {
            double x = scan.nextDouble();
            m = m + 1;
            sum = sum + x;
        }

        System.out.println(m + " numbers sum to " + sum);
        System.out.println(m + " numbers average is " + (sum / m));
        scan.close();
    }
}

Execution of the above program results in (enter a non-numeric value to end the input):

$ javac ScannerDemo.java
$ java ScannerDemo
Please enter numbers:
12
23
15
21.4
end
4 numbers sum to 71.4
4 numbers average is 17.85

For more information, refer to the API documentation: https://www.tutorialpro.org/manual/jdk11api/java.base/java/util/Scanner.html. ```

❮ Java String Startswith Java String Contains ❯