only numeric numbers with control

Firstly I'm a new person here. I need to ask one question.

Scanner klavye = new Scanner(System.in);

System.out.println("DDD-DD-DDDD enter bank number digit: ");
String hesapNo = klavye.nextLine();

if(hesapNo.length() != 11) {
   System.out.println("You need to enter number with 11 digit");
}
else {
   if(hesapNo.charAt(3) == '-' && hesapNo.charAt(6) == '-') {
       System.out.println(hesapNo + " is valid");
   }
   else {
      System.out.println(hesapNo + " is not valid");
   }
}

I want to take only digit number but If I write below like this: ABC-DC-SMND "The count is valid" how can I solve this problem?

Thanks for all of your interest.

2 answers

  • answered 2018-01-11 19:52 Juan Carlos Mendoza

    That can be done with a simple regex using String.matches:

    Scanner klavye = new Scanner(System.in);
    
    System.out.println("DDD-DD-DDDD enter bank number digit: ");
    String hesapNo = klavye.nextLine();
    
    if(hesapNo.matches("\\d{3}-\\d{2}-\\d{4}")){ // <-- this regex matches your pattern DDD-DD-DDDD
        System.out.println(hesapNo + " is valid");
    }else{
        System.out.println("You need to enter number with 11 digit");
    }
    

    EDIT

    If you want to keep asking for input until a valid one is entered then you can do this:

    Scanner klavye = new Scanner(System.in);
    String hesapNo;
    boolean validInput;
    
    System.out.println("DDD-DD-DDDD enter bank number digit: ");
    do {
        hesapNo = klavye.nextLine();
        validInput = hesapNo.matches("\\d{3}-\\d{2}-\\d{4}");
        if (!validInput) { // if invalid input then warn the user
            System.out.println("Your bank number must be in DDD-DD-DDDD format");
        }
    } while (!validInput); // loop until a valid input is provided
    System.out.println(hesapNo + " is valid");
    

  • answered 2018-01-11 19:52 Onur A.

    You can do it with regular expressions and a loop to prompt the user until a valid input.

    Scanner klavye = new Scanner(System.in);
    
    System.out.println("DDD-DD-DDDD enter bank number digit: ");
    String hesapNo;
    final String regexPattern = "\\d{3}-\\d{2}-\\d{4}";
    do {
       hesapNo = klavye.nextLine();
       System.out.println("You need to enter a number with 11 digit with pattern: DDD-DD-DDDD");
    }
    while(!hesapNo.matches(regexPattern));
    
    System.out.println(hesapNo + " is valid");