0

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()
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
madman75
  • 56
  • 1
  • 8
  • 3
    Why don't you just remove additional spaces instead of annoying the user with it? – mhafellner Jul 22 '13 at 15:08
  • because the input can have at least 1 consecutive whitespace between words. its when the user enters 2 consecutive whitespaces is when there should be an error. – madman75 Jul 22 '13 at 15:11

3 Answers3

0

For explanation how to replace multiple spaces with single space read how-to-replace-2-or-more-spaces-with-single-space-in-string.

Community
  • 1
  • 1
mhafellner
  • 458
  • 3
  • 9
0

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);
Community
  • 1
  • 1
htulipe
  • 1,575
  • 1
  • 10
  • 22
0
String str = "Sam  ple";
Pattern pattern = Pattern.compile("\\s{2,}");
Matcher matcher = pattern.matcher(str);
boolean check = matcher.find();
bensiu
  • 24,660
  • 56
  • 77
  • 117
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64