2014-03-06 112 views
-5

有人能告诉我一个代码,用于检查字符串中特定数量的空格。如何检查空格的字符串

示例:用户输入的字符串需要正好具有3个空格,例如“0 4 0 1”我需要一个代码来检查每个数字之间是否有空格。

这里是我的尝试吧:

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; 
    } 
} 
+0

不错的要求。请展示一些努力 – Sanjeev

+0

我很抱歉,我试图尝试解决这个问题。 – MikeJ

回答

1

可以知道whitespaces用户通过这样做,有多少进入:

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

编辑:您可以通过更改您的while解决你的问题条件是这样的:

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

不是我所在的地方。你能检查我的完整代码吗?对不起,但我是初学者 – MikeJ

+0

@MikeJ什么是'keyboard',什么是'guessSpace'?只需发布您的完整代码 – Baby

+0

键盘是扫描仪。它正在接受用户的输入。我的代码是一个游戏,用户输入一个字母,然后检查空格。有点像hang子手。 guessSpace是用户正在检查的空间。在这个循环中,我正在检查用户是否输入了正确数量的空间来检查。所以我需要确保它们都是数字,并且用户还指示4个空格进行检查。 – MikeJ

0
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; 
     }