Write a java program check Number Validation.

Write a program to read a string of 10 digit number, check whether the string contains a 10 digit number in the format XXX-XXX-XXXX where ‘X’ is a digit(Number Validation).

Input and Output Format:

Input consists of a string.

The output is a string specifying the given string is valid or not.

Refer sample output for formatting specifications.

Sample Input 1:

123-456-7895

Sample Output 1:

Valid number format

Sample Input 2:

-123-12344322

Sample Output 2:

Invalid number format

Number Validation in Java.

import java.util.Scanner;


public class Main2 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
     String s1 = sc.nextLine();
    
    if(s1.matches("[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}")){
      System.out.println("Valid number format");
    }else{
      System.out.println("Invalid number format");
    }
  }

}

Add a Comment

Your email address will not be published. Required fields are marked *

13 − 2 =