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.example.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.

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.example.network;

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 53
localhost is listening on port 80
localhost is listening on port 443
localhost is listening on port 631
localhost is listening on port 1099
localhost is listening on port 3306
localhost is listening on port 4380
localhost is listening on port 6942
localhost is listening on port 8005
localhost is listening on port 8009
localhost is listening on port 8021
localhost is listening on port 8080
...