如何按数组

时间:2016-03-29 18:29:17

标签: java for-loop arraylist while-loop

我最近开始学习计算机科学课程,以便更多地了解编程,并且似乎已经在我们的ArrayLists实验室遇到了障碍。该程序的目的是将x个字符串放入ArrayList中,然后按降序输出结果。

Ex:Zebra,Deer,Giraffe 鹿

结果:长颈鹿,斑马,鹿

我在网上看了一下,发现了几个使用ArrayList比较器的例子,但我们的教授希望我们通过过滤掉最大的单词,打印它,删除它然后继续循环直到打印出所有单词来完成它。 / p>

到目前为止,这是我的代码:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int length = 0;
    String longest = "";
    String currentWord = "";
    ArrayList <String> DescendArray = new ArrayList<String>();
    System.out.println("What would you like to add to the list?");
    String userInput = input.next();
    while(!userInput.equals("d"))
    {
        DescendArray.add(userInput);
        userInput = input.next();
    }
    for (int i=0; i < DescendArray.size(); i++)
    {
        if (DescendArray.get(i).length() > longest.length())
                {
                    currentWord = DescendArray.get(i);
                    if (currentWord.length() > longest.length())
                    {
                        longest = currentWord;
                        length = longest.length();
                    }
                }
        for (int j=1; j < DescendArray.size() -1 ; j++)
        {
            if (DescendArray.get(j - 1).length() > longest.length())
            {
                DescendArray.remove(j - 1);
            }
            System.out.println(longest + " " + length);
        }
    }
}

}

我假设我的错误在内循环中的某个地方,但无论我使用多少不同的变体,我似乎无法使其工作。

10 个答案:

答案 0 :(得分:3)

这基本上就是你要做的事情:

public class Zoo {

    public static void main(String[] args) {
        List<String> zoo = new ArrayList<String>();
        zoo.add("Zebra");
        zoo.add("Deer");
        zoo.add("Giraffe");
        zoo.add("Deer");
        while(!zoo.isEmpty()) {
            String bigger = "";
            for(String animal : zoo) {
                if(animal.length() > bigger.length()) {
                    bigger = animal;
                }
            }
            System.out.println(bigger);
            while(zoo.contains(bigger)) {
                zoo.remove(bigger);
            }
        }
    }

}

答案 1 :(得分:2)

尝试一下,它对我有用。

rätt[se]

答案 2 :(得分:1)

这似乎有效。如果您不想删除重复的动物,请删除distinct()方法。我省略了列表的创建。

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Zoo {
    public static void main(String[] args) {
        List<String> zoo = Arrays.asList("Zebra", "Deer", "Giraffe", "Deer");
        String output = zoo.stream()
                           .distinct()
                           .sorted((x, y) -> Integer.compare(y.length(), x.length()))
                           .collect(Collectors.joining(","));
        System.out.println(output);
    }
}

答案 3 :(得分:1)

我对其他解决方案的冗长感到惊讶。一个更简单的方法是使用流:

List<String> original = Arrays.asList("s1", "String 2", "ss3", "s");
List<String> sorted = original.stream()
        .sorted((s1, s2) -> s2.length() - s1.length())
        .collect(Collectors.toList());
System.out.println(sorted);

将“原始”替换为您的ArrayList。

答案 4 :(得分:0)

假设不需要同时删除重复的单词,以便按顺序删除重复的单词,并且不需要按字母顺序完成列表(可以先对列表进行排序),以及那个线程的安全性并不重要,我会避免使用整数计数器并检查大小。相反,我会运行输出循环,直到删除所有内容。

举个例子:

public void doRemove()
{
    while (! descendArray.isEmpty()) {
        String longest = "";

        for (String s : descendArray) {
            if (s.length() > longest.length()) {
                longest = s;
            }
        }

        if (longest.length() > 0) {
            if (descendArray.remove(longest)) {
                System.out.println(longest + " (" + longest.length() + ")");
            }
        }
    } // while we stil have things to process
}

答案 5 :(得分:0)

问题似乎是,对于你的for循环中的每次迭代,你到达长颈鹿作为你最长的单词,然后你要检查列表的其余部分,看它是否比长颈鹿更长。而不是你现在拥有的东西,我会写一些类似的东西:

for (int i=0; i < DescendArray.size(); i++)
{
    longest = "";
    length = longest.length();
    int longestIndex = 0;
    for (int j=1; j < DescendArray.size() -1 ; j++)
    {
        currentWord = DescendArray.get(j);
        if (currentWord.length() > longest.length())
        {
            longestIndex = j;
            longest = currentWord;
            length = longest.length();
        }
    }
    DescendArray.remove(longestIndex);
    System.out.println(longest + " " + length);
}

这个嵌套for循环应首先找到最长的单词,存储索引并打印并删除该索引处的条目,然后才能找到下一个最长的条目。

答案 6 :(得分:0)

当你说降序时你是指字符串的长度还是字母比较?

查看QuickSort algorithm如何用于字符串排序。您可以找到information on QuickSort here

答案 7 :(得分:0)

这是另一种可以使用的变体,但涉及额外的数组列表:

ArrayList<String> DescendArray = new ArrayList<>();
DescendArray.add("Monkey");
DescendArray.add("Giraffe");
DescendArray.add("Hippo");
DescendArray.add("Zebra");
DescendArray.add("Monkey");

List<String> copy = new ArrayList<>(DescendArray);

for (int i=0; i<DescendArray.size(); i++) {
    String longest = "";
    for (int j=0; j<copy.size(); j++) {
        String current = copy.get(j);
        if (current.length() > longest.length()) {
             longest = current;
        }
    }
    System.out.println(longest);
    while(copy.contains(longest)) {
        copy.remove(longest);
    }        
}

答案 8 :(得分:0)

当你需要从列表中删除元素时,迭代器是一种更好的方法。请参阅下面的代码。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class Zoo {
    public static void main(String[] args) {
        List<String> zoo = new ArrayList<String>();
        zoo.add("Zebra");
        zoo.add("Deer");
        zoo.add("Giraffe");
        zoo.add("Deer");
        Collections.sort(zoo,new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {          
                return o2.compareTo(o1);
            }
        });
        Iterator<String> iterator=zoo.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            iterator.remove();
        }
    }
}

答案 9 :(得分:0)

要根据每个字符串长度对ArrayList进行排序,您可以尝试:

private ArrayList SortwithStrlength(ArrayList templist) {
        for(int i=0;i<templist.size();i++)
        {
            for(int j=0;j<templist.size();j++)
            {
                String temp;
                if(templist.get(i).toString().length()<templist.get(j).toString().length())
                {
                    temp=templist.get(i).toString();
                    templist.set(i, templist.get(j).toString());
                    templist.set(j,temp);
                }
            }
        }
        return templist;
    }