简体   繁体   中英

How to re-prompt a user for input if they enter a string with multiple whitespaces

So i am wondering how I can check a string that has been inputed by the user for multiple spaces, and if it does have multiple spaces between words, i want the user to be re-prompted for input. I am using a do- while loop. here is the format:

Scanner scanner01 = new Scanner(System.in);
String inputLast;
do {
    System.out.println("Enter a valid LAST name: ");
    inputLast = scanner01.nextLine();
} while()

有关如何用单个空格替换多个空格的说明,请阅读如何使用字符串中的单个空格替换2或更多空格

One solution would be this (based on this answer ):

   Scanner scanner01 = new Scanner(System.in);
   String inputLast;
   do {
       System.out.println("Enter a valid LAST name: ");
       inputLast = scanner01.nextLine();
       if(inputLast.length() - inputLast.replaceAll(" ", "").length() <= 1){
           break;
       }
   } while(true);
String str = "Sam  ple";
Pattern pattern = Pattern.compile("\\s{2,}");
Matcher matcher = pattern.matcher(str);
boolean check = matcher.find();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM