2014-03-06 110 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; 
     }