How do I validate input when using Scanner?

This example show you how to validate input when using java.util.Scanner. To validate input the Scanner class provides some hasNextXXX() method that can be use to validate input. For example if we want to check whether the input is a valid integer we can use the hasNextInt() method.

In the code snippet below will demonstrate how to validate whether the user provide a positive integer number. The program will repeat until the correct input is supplied.

package org.kodejava.util;

import java.util.Scanner;

public class ScannerValidateInput {
    public static void main(String[] args) {
        ScannerValidateInput demo = new ScannerValidateInput();
        demo.validatePositiveNumber();
    }

    private void validatePositiveNumber() {
        Scanner scanner = new Scanner(System.in);

        int number;
        do {
            System.out.print("Please enter a positive number: ");
            while (!scanner.hasNextInt()) {
                String input = scanner.next();
                System.out.printf("\"%s\" is not a valid number.%n", input);
            }
            number = scanner.nextInt();
        } while (number < 0);

        System.out.printf("You have entered a positive number %d.%n", number);
    }
}

The output produce by the snippet:

Please enter a positive number: qwerty
"qwerty" is not a valid number.
@@@
"@@@" is not a valid number.
-100
Please enter a positive number: 99
You have entered a positive number 99.

Another example is to validate if user correctly input letters to guest a secret word. In the code snippet below if the user does not enter a letter the code will keep asking for a valid letter. It loops until the length of the inputted letters equals to the length of secret word.

package org.kodejava.util;

import java.util.Scanner;

public class ScannerValidateLetter {
    public static void main(String[] args) {
        ScannerValidateLetter demo = new ScannerValidateLetter();
        demo.validateLetter();
    }

    private void validateLetter() {
        String secretWord = "Hello";
        Scanner scanner = new Scanner(System.in);

        int length = 0;
        StringBuilder guess = new StringBuilder();
        do {
            System.out.print("Enter a letter to guess: ");
            char letter = scanner.next().charAt(0);
            if (Character.isLetter(letter)) {
                guess.append(letter);
                length++;
            }
        } while (length < secretWord.length());

        if (secretWord.equalsIgnoreCase(guess.toString())) {
            System.out.println("You are correct!");
        } else {
            System.out.println("Please try again!");
        }
    }
}
Enter a letter to guess: 1
Enter a letter to guess: 2
Enter a letter to guess: H
Enter a letter to guess: e
Enter a letter to guess: l
Enter a letter to guess: l
Enter a letter to guess: o
You are correct!

How do I create port scanner program?

In this example you’ll see how to create a simple port scanner program to check the open ports for the specified host name.

package org.kodejava.net;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class PortScanner {
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        InetAddress inetAddress = InetAddress.getByName(host);

        String hostName = inetAddress.getHostName();
        for (int port = 0; port <= 65535; port++) {
            try {
                Socket socket = new Socket(hostName, port);
                String text = hostName + " is listening on port " + port;
                System.out.println(text);
                socket.close();
            } catch (IOException e) {
                // empty catch block
            }
        }
    }
}

The result of the code snippet above are:

localhost is listening on port 21
localhost is listening on port 80
localhost is listening on port 135
localhost is listening on port 445
localhost is listening on port 3000
...
...
localhost is listening on port 63342
localhost is listening on port 63467
localhost is listening on port 64891
localhost is listening on port 64921
localhost is listening on port 65001

How do I split a string using Scanner class?

Instead of using the StringTokenizer class or the String.split() method we can use the java.util.Scanner class to split a string.

package org.kodejava.util;

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

public class ScannerTokenDemo {
    public static void main(String[] args) {
        // This file contains some data as follows:
        // a, b, c, d
        // e, f, g, h
        // i, j, k, l
        File file = new File("data.txt");
        try {
            // Here we use the Scanner class to read file content line-by-line.
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();

                // From the above line of code we got a line from the file
                // content. Now we want to split the line with comma as the 
                // character delimiter.
                Scanner lineScanner = new Scanner(line);
                lineScanner.useDelimiter(",");
                while (lineScanner.hasNext()) {
                    // Get each split data from the Scanner object and print
                    // the value.
                    String part = lineScanner.next();
                    System.out.print(part + ", ");
                }                
                System.out.println();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

How do I read file line by line using java.util.Scanner class?

Here is a compact way to read file line by line using the java.util.Scanner class.

package org.kodejava.util;

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

public class ScannerReadFile {
    public static void main(String[] args) {
        // Create an instance of File for data.txt file.
        File file = new File("README.md");
        try {
            // Create a new Scanner object which will read the data
            // from the file passed in. To check if there are more 
            // line to read from it, we call the scanner.hasNextLine() 
            // method. We then read line one by one till all lines 
            // is read.
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

How do I read user input from console using java.util.Scanner class?

In JDK 1.5 a java.util.Scanner class was introduced to handle user input in console application. This class enable us to read string, integer, long, etc.

package org.kodejava.util;

import java.util.Scanner;

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

        // Read string input for username
        System.out.print("Username: ");
        String username = scanner.nextLine();

        // Read string input for password
        System.out.print("Password: ");
        String password = scanner.nextLine();

        // Read an integer input for another challenge
        System.out.print("What is 2 + 2: ");
        int result = scanner.nextInt();

        if (username.equals("admin")
                && password.equals("secret") && result == 4) {
            System.out.println("Welcome to Java Application");
        } else {
            System.out.println("Invalid username or password, " +
                    "access denied!");
        }
    }
}

The result of the code snippet:

Username: admin
Password: secret
What is 2 + 2: 4
Welcome to Java Application