2016-08-07 138 views
1

我正在開發軟件測試課程。我需要創建一個循環遍歷一個字符串,以便找到一個特定的單詞,然後將其與預期結果進行比較。我遇到的問題是我的循環只打印出字符串的第一個單詞。我不能爲了我的生活找出我做錯了什麼。請幫忙。僅循環打印第一個字

這裏是我的代碼:

String input = "Now is the time for all great men to come to the aid of their country"; 
String tempString = ""; 
char c = '\0'; 
int n = input.length(); 
for(int i = 0; i<n; i++) 
{ 
    if(c != ' ') 
    { 
     c = input.charAt(i); 
     tempString = tempString + c; 
    } 
    else 
    { 
     System.out.println(tempString); 
     tempString = ""; 
    } 
} 

回答

3

原因無它,只打印出的第一個詞是,一旦一個空間找到你永遠不要重置C的值,因此如果老是會是假的,並會打印出您設置爲空字符串的tempString。

要解決,你所編寫的代碼:

public static void main(String[] args) { 
    String input = "Now is the time for all great men to come to the aid of their country"; 
    String tempString = ""; 
    char c = '\0'; 
    int n = input.length(); 
    for(int i = 0; i<n; i++) 
    { 
     c = input.charAt(i); // this needs to be outside the if statement 
     if(c != ' ') 
     { 
      tempString = tempString + c; 
     } 
     else 
     { 
      System.out.println(tempString); 
      tempString = ""; 
     } 
    } 
} 

但是......它的很多清潔劑只需使用內置的字符串的方法做你想做的(例如拆分出來的空間)是什麼。由於分割方法返回一個字符串數組,因此您也可以簡單地爲每個循環使用一個循環:

public static void main(String[] args) { 
    String input = "Now is the time for all great men to come to the aid of their country"; 
    for (String word : input.split(" ")) { 
     System.out.println(word); 
    } 
} 
2

你應該之外的if移動的c設置。否則,你比較之前的字符,而不是比較當前的字符。

c = input.charAt(i); // <<== Move outside "if" 
if(c != ' ') 
{ 
    tempString = tempString + c; 
} 
0

考慮使用split代替

String input = "Now is the time for all great men to come to the aid of their country"; 

String arr[] = input.split (" "); 

for (int x = 0; x < arr.length; x++) { 
    System.out.println (arr[x]); // each word - do want you want 
}