2016-08-07 137 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 
}