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.

How do I read file using Scanner class?

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

package org.kodejava.example.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("data.txt");
        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 check by calling the 
            // scanner.hasNextLine() method. We then read line one 
            // by one till all line is read.
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}