首先,我是新来的人。我需要问一个问题。

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");
   }
}


我只想输入数字,但是如果我这样写:
ABC-DC-SMND
“计数有效”
我怎么解决这个问题?

感谢您的关注。

最佳答案

您可以使用正则表达式和循环来提示用户,直到输入有效为止。

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");

09-12 11:21