只有带控件的数字

时间:2018-01-11 19:52:25

标签: java string integer

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

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 "计数有效" 我该如何解决这个问题?

感谢您的所有兴趣。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

可以使用regex

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

修改

如果您想要输入有效输入,那么您可以这样做:

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