JAVA - 了解列表循环

问题描述 投票:0回答:1

编写一个方法removeShorterStringsList,该方法将List作为参数,并从每个连续的值对中删除该对中较短的字符串。

例如,假设名为 list 的 ArrayList 包含以下值: {"four", "score", "and", "seven", "years", "ago"} removeShorterStringsList 将打印出 {"score", "七”、“年”}.

使用 {"hello", "good", "morning"}; 时,只要 size() 为奇数,就会打印出 {"hello", "morning"} 故意忽略最后一个元素。

我的方法适用于具有偶数 size() 的列表。但是,当我通过具有奇数 size() 的列表运行我的方法时,我收到索引越界错误。不知道为什么会发生这种情况,因为我有一个增加 i 的条件。我在处理大小为 3 的列表时遇到问题。如果忽略最后一个元素并且我们运行此循环,那么它不应该在循环一次后停止吗,因为 i 从 0 开始,在底部 (1) 递增,然后再次在顶部 (2) 然后 2<2 would stop the loop? Heres my method:

public static void removeShorterStringsList(List<String> a) {
        int size = a.size();
        for(int i = 0; i<size-1; i++){
            // debugging code: System.out.println(a);
            String one = a.get(i);
            String two = a.get(i+1);
            if(one.length() == 0 || two.length() == 0){
                throw new IllegalArgumentException("String is empty");
            }
            if(one.length() > two.length() || // if the first string is greater than or equal     to
            one.length() == two.length()){    // the second string, the second string is removed
                a.remove(two);
            } else {
                a.remove(one); // first string is removed if it has a smaller size than the     second
            }
            if(size%2 != 0){ // increments i if we are looping through an odd number of strings
                i++;
            }
        }
    }
java for-loop arraylist
1个回答
0
投票

当您删除时,您的列表大小会更短,但您的情况我< size-1 is i < 6( for explame : {"four", "score", "and", "seven", "years", "ago"} ) so when your list.size become lower than i , it will be error;

也许你可以改变:

for(int i = 0; i for(int i = 0; i

© www.soinside.com 2019 - 2024. All rights reserved.