ในบางกรณีเราอาจจะต้องรับเอาตัวเลขที่เป็นข้อความมาประมวลผล ซึ่งต้องแปลงชนิดของข้อมูลจาก String มาเป็น int ก่อน แต่หากข้อความนั้นไม่ได้มีเฉพาะตัวเลขเราจะเจอข้อผิดพลาดว่า NumberFormatException: For input string: “xxxxx” วิธีการป้องกันคือเราต้องตรวจสอบก่อนว่าข้อความที่จะรับมาเป็นตัวเลขล้วนๆหรือไม่ด้วยเมธอด matches ของคลาส String ตามตัวอย่างด้านล่าง (input.matches(“\d+”))

import java.util.Scanner;

public class NumberFormatExceptionDemo {

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

        if (input.matches(“\\d+”)) { // it checks the input line contains only digits
            int number = Integer.parseInt(input);
            System.out.println(number + 1);
        } else {
            System.out.println(“Incorrect number: ” + input);
        }
    }
}