Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Taking Input using Scanner Class in Java

[post-views]

 

 

In this lesson, you will learn,

  • Understanding Scanner Class
  • Methods of Scanner Class

 

1. Scanner Class

  • The Scanner class in Java is part of the java.util package.
  • It provides a simple and flexible way to read data of various types (int, float, double, etc.) from different sources, including input streams (like standard input), files, and strings.

 

Using Scanner Class to Take Input

You will create an instance of the Scanner class first as follows

//Creates a Scanner object that reads 
//from standard input (keyboard).

Scanner scanner = new Scanner(System.in);

Now, the object scanner can be used to read inputs from the keyboard.

 

Example 1: Reading from Standard Input

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
 
        //Create a Scanner object to read from console
        Scanner scanner = new Scanner(System.in); 
 
        System.out.print("Enter your full name: ");
        // Reads a whole line of text
        String name = scanner.nextLine(); 
        System.out.println("Hello, " + name + "!");
 
        System.out.print("Enter your age: ");
        // Reads an integer value
        int age = scanner.nextInt(); 
        System.out.println("You are " + age + " years old.");
         
        //Close the scanner when it's no longer needed
        scanner.close(); 
    }
}

 

Output

Enter your full name: Amit Kumar
Hello, Amit Kumar!
Enter your age: 29
You are 29 years old.

 

Explanation

In this example, a Scanner object is created to read data from the standard input (keyboard).

The nextLine() method reads a string (until the user presses Enter), and the nextInt() method reads an integer.

 

Similar to nextInt() method, the nextFloat(), nextDouble(), and nextLong() methods can be used to take float, double, and long values.

 

Methods of Scanner Class

Below is a table summarizing some of the common methods of the Scanner class in Java, their purposes, and example usages:

Method Description Example Usage
next() Finds and returns the next complete token from this scanner. String s = scanner.next();
nextLine() Advances this scanner past the current line and returns the input that was skipped. String line = scanner.nextLine();
nextInt() Scans the next token of the input as an int. int i = scanner.nextInt();
nextDouble() Scans the next token of the input as a double. double d = scanner.nextDouble();
nextFloat() Scans the next token of the input as a float. float f = scanner.nextFloat();
nextLong() Scans the next token of the input as a long. long l = scanner.nextLong();
hasNext() Returns true if this scanner has another token in its input. boolean b = scanner.hasNext();
hasNextInt() Returns true if the next token in this scanner’s input can be interpreted as an int. boolean b = scanner.hasNextInt();
hasNextDouble() Returns true if the next token in this scanner’s input can be interpreted as a double. boolean b = scanner.hasNextDouble();
useDelimiter(String pattern) Sets this scanner’s delimiting pattern to the specified pattern. scanner.useDelimiter(",");
close() Closes this scanner. scanner.close();

 

next() Method of Scanner Class

  • The next() method of the Scanner class in Java is used to find and return the next complete token from the input source.
  • A token is typically a word, which is considered to be delimited by whitespace.

 

Example of next() Method

import java.util.Scanner;

public class NextMethodExample {
    public static void main(String[] args) {
        // Create a Scanner object 
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a line of text:");
        String firstWord = scanner.next(); // Reads the first word
        String secondWord = scanner.next(); // Reads the second word

        System.out.println("First word: " + firstWord);
        System.out.println("Second word: " + secondWord);

        // It's always a good practice to close the scanner
        scanner.close();
    }
}

 

Output

Enter a line of text:
Hello World from Java
First word: Hello
Second word: World

 

Explanation

The next() method only reads up to the first occurrence of whitespace, effectively parsing the input into individual tokens that can be processed separately.

Note that in this example, if you enter more than two words, only the first two will be processed because we only called next() twice.

 

Additional calls to next() would continue to return subsequent tokens from the input.

 

Advanced Usage: Using Delimiters

Using Different Delimiters: The Scanner can use custom delimiters instead of whitespace.

Scanner scanner = new Scanner("apple, banana, cherry");
scanner.useDelimiter(", ");

while (scanner.hasNext()) {
    System.out.println(scanner.next());
}

scanner.close();

 

In this case, the scanner is using a comma followed by a space as the delimiter to tokenize the input string.

 

Example of hasNextInt() Method

The hasNextInt() method of the Scanner class in Java is used to check if the next token in the scanner’s input can be interpreted as an int value in the default radix.

package ch3;

import java.util.Scanner;

public class HasNextIntExample {
    public static void main(String[] args) {
        // Create a Scanner object 
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a list of integer values. "
        		+ "Enter any non-integer to stop:");

        // Continuously read intesgers from the console
        while (scanner.hasNextInt()) {
            int value = scanner.nextInt();
            System.out.println("You entered the integer: " + value);
        }

        System.out.println("Non-integer input detected. Exiting...");

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

 

Output

Enter a list of integer values. Enter any non-integer to stop:
10 20 30 34.5
You entered the integer: 10
You entered the integer: 20
You entered the integer: 30
Non-integer input detected. Exiting...

 

Note: It allows you to ensure that the next input can be safely read as an integer before attempting to read it, thereby avoiding InputMismatchException.

 

Key Features of Scanner Class

1. Parsing of Primitive Types and Strings:

  • The Scanner class can read and parse various data types including int, long, double, float, byte, short, boolean, and String.
  • It achieves this by providing specific methods like nextInt(), nextDouble(), nextBoolean(), nextLine(), etc.

2. Tokenization

  • It tokenizes the input based on a delimiter. Whitespace is by default delimiter.
  • You can change the delimiter using the useDelimiter(String pattern) method.

3. Flexible Source of Input

  • It can read data from InputStream (like System.in), File, Path, or String.

 

Bonus! More Examples Using Scanner

 

Example: Check Even or Odd

import java.util.Scanner;

public class EvenOddChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int num = scanner.nextInt();

        if (num % 2 == 0) {
            System.out.println(num + " is even.");
        } else {
            System.out.println(num + " is odd.");
        }

        scanner.close();
    }
}

 

Example: Simple Interest Calculator

import java.util.Scanner;

public class InterestCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter principal amount: ");
        double principal = scanner.nextDouble();

        System.out.print("Enter rate of interest (in %): ");
        double rate = scanner.nextDouble();

        System.out.print("Enter time (in years): ");
        double time = scanner.nextDouble();

        double interest = (principal * rate * time) / 100;
        System.out.println("Simple Interest: " + interest);

        scanner.close();
    }
}

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

14/01/2025

good

 

 

Submit a Review