C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Java Program: Input Validation - Numeric Only

import java.util.Scanner;

 

public class NumericInputValidation {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number: ");

 

        // Check if input is numeric

        if (sc.hasNextInt()) {

            int number = sc.nextInt();

            System.out.println("Valid number entered: " + number);

        }

        else if (sc.hasNextDouble()) {

            double number = sc.nextDouble();

            System.out.println("Valid number entered: " + number);

        }

        else {

            System.out.println("Invalid input! Please enter numeric values only.");

        }

 

        sc.close();

    }

}

Output

 
OUTPUT 1: Integer Input
Enter a number: 123
Valid number entered: 123 

OUTPUT 2: Floating Point Input
Enter a number: 45.67
Valid number entered: 45.67
 
OUTPUT 3: Invalid Input
Enter a number: abc
Invalid input! Please enter numeric values only.

Explanation

1. Scanner Methods

  • hasNextInt() → checks if the next token is an integer
  • hasNextDouble() → checks if the next token is a floating-point number

2. Why Input Validation?

  • Prevents runtime errors when parsing non-numeric input
  • Ensures only valid numeric values are processed

3. Flow

  1. Ask the user for input
  2. Check using hasNextInt() → integer
  3. Else check hasNextDouble() → floating number
  4. Else → invalid input message