Question

Can someone show me a code for how to check for a SPECIFIC amount of spaces in a string.

Example: User's entered string needs to have exactly 3 white spaces, such as "0 4 0 1" I need a code that will check that there's a space in between each number.

Here was my try at it:

String guessedSpacesCheck = "[0-9]+";
boolean b2 = guessedSpaces.matches(guessedSpacesCheck);
int totalSpace=guessedSpaces.split(" ").length-1;

boolean isSpaceValid = totalSpace==whiteSpace;

while (b2==false && isSpaceValid==false)
{
    System.out.println("Your input is not valid. Try again.");
    System.out.print("Please enter the letter you want to guess: ");
    letterGuess = keyboard.next().charAt(0);

    System.out.print("Please enter the spaces you want to check (separated by spaces): ");
    guessedSpaces = guessSpace.nextLine();

    guessedSpaces.matches(guessedSpacesCheck);
    if (guessedSpaces.matches(guessedSpacesCheck)==true && isSpaceValid==true)
    {
        b2=true;
        isSpaceValid=true;
    }
}
Was it helpful?

Solution

You can know how many whitespaces user entered by doing this:

Scanner sc = new Scanner(System.in);
System.out.println("Enter word with white-spaces:");
String str = sc.nextLine();
int totalSpace = str.split(" ").length-1;
System.out.println("total white-spaces is:"+totalSpace);

Edit: You can solve you problem by changing your while condition like this:

 while(!(guessedSpaces.replaceAll("\\d","").length()==3 && guessedSpaces.split(" ").length-1==3)){
    .....
    .....
    System.out.println("Enter word with white-spaces:");
    guessedSpaces = keyboard.nextLine();
}

OTHER TIPS

 function check(evt) {
    var id= document.getElementById('Id').value;
    if(evt.keyCode == 32){
        alert("Sorry, you are not allowed to enter any spaces");    
        evt.returnValue = false;
        document.getElementById('Id').value='';     
       return false;
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top