java - for循环没有完全迭代

标签 java string loops for-loop iteration

我正在尝试创建一个算法来测试给定字符串是否是字符串列表的覆盖字符串。如果字符串包含其中从左到右顺序的每个字符串中的字符,则该字符串是字符串列表的覆盖字符串。例如,“house”和“hotel”的覆盖字符串是“ahogjutsel”,非覆盖字符串的示例是“ahogjsutel”。

我面临的问题是我的 for 循环在返回输出之前只完成了一次迭代。我试图一个一个地遍历列表中的每个字符串,检查每个字符的索引以确保保持从左到右的顺序。

关于如何修改我的 for 循环以便算法遍历每个字符串中的每个字符的任何建议都将非常有帮助。

公共(public)类字符串处理{

//Array list to add list of strings for testing.
public static ArrayList<String> stringList = new ArrayList<>();

public static String list1 = "abc";

public static String list2 = "def";  


//Algorithm to iterate through each word in stringList and test if it appears in the cover string
//by testing index values.
public static boolean isCover(String coverString){
    boolean isCover = false;
    stringList.add(list1);
    stringList.add(list2);
    int size = stringList.size();
    int coverSize = coverString.length();

for (int i = 0; i < (size -1) ; i ++){
        for (int j = 0; j<stringList.get(i).length(); j++){              

        if (coverString.indexOf(stringList.get(i).charAt(j)) < coverString.indexOf(stringList.get(i).charAt(j+1))){
            return true;
        }
        else
            return isCover;
        }     
}
return isCover;
}


public static void main(String[] args) {

//For loop only checks if a is before b, then returns true before checking the rest of the characters and strings.
    System.out.println(StringProcessing.isCover("abfdec"));

}
}

最佳答案

  1. 在您的 if 条件中,您将返回一个值,这将结束您的循环。

  2. 编辑将字符串数组列表与字符串进行比较。

    编辑 2015 年 11 月 30 日:在确定单词是否为覆盖字符串时考虑了字母顺序。

改变你的方法:

public class StringProcessing2 {
public static ArrayList<String> stringList = new ArrayList<>();
//Negative Case
public static String list1 = "house";
public static String list2 = "hotel";  

//Positive Case
//public static String list1 = "abc";
//public static String list2 = "def";  


public static boolean isCover(String word){
    int matchedWords = 0;
    stringList.add(list1);
    stringList.add(list2);

    for(int i = 0; i < stringList.size(); i++){
            if(word.contains(String.valueOf(stringList.get(i)) )){
                matchedWords++;                                
      }
}
    if(matchedWords == stringList.size()){
        return true;
    }
    else
        return false;           
}


public static void main(String[] args) {
 System.out.println(isCover("ahogjutsel"));
}
}

关于java - for循环没有完全迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33989637/

相关文章:

javascript - 替换字符串中的值

javascript - 如何根据选择框值将 div 复制一定次数?

java - 如何抑制丢失 `throws` 的错误

java - 为什么 ConcurrentHashMap 使用局部变量 `tab` 来引用表?

c++ - 在 C++ 中读取大字符串——有安全快速的方法吗?

regex - 如何从 Perl 中的字符串中提取子字符串?

javascript - 更改 forEach 循环中的状态

java - 如何从Android中的 fragment 启动相机

java - 在java中的同一行中打印

python - 将字符串差异与字符串列表进行比较