2016-08-07 8 views
1

私はソフトウェアテストクラスのプログラムに取り組んでいます。私は、特定の単語を見つけてそれを期待される結果と比較するために、文字列を反復するループを作成する必要があります。私が抱えている問題は、ループが文字列の最初の単語だけを出力することです。私の人生は私が間違っていることを理解することはできません。助けてください。あなたはifcの設定を移動する必要がありループ印刷の最初の単語のみ

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の値をリセットしないことをされた場合は、常に意志falseの場合は、空文字列に設定した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 = ""; 
     } 
    } 
} 

しかし...それは単にあなたが(例えばスペース上で分割)やりたい文字列の方法で構築を使用するために多くのクリーナーです:あなたが書いたように、コードを修正すること

。 splitメソッドは文字列配列を返すので、各ループに対して単にaを使用することもできます。

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

は、ここに私のコードです。そうでない場合は、現在の文字を比較するのではなく、よりも先に文字を比較します。

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 
} 
関連する問題