ArrayLists数组?

时间:2013-03-21 16:25:37

标签: java arrays arraylist

我正在使用一组arraylists来存储字符串中的单词。我按照单词的长度将它们存储在数组列表数组中。我现在正在使用switch语句,但是我必须按照我的方式进行45个案例,而且我想知道是否有人知道我可以执行相同操作的更简单和更短的方式。这是一些代码:

    String temp;
    Scanner sc = new Scanner(str);
    while(sc.hasNext())
    {
        temp = sc.next();

        switch(temp.length()){

        case 1:
            wordsByLen[0].add(temp);
        case 2:
            wordsByLen[1].add(temp);
        case 3:
            wordsByLen[2].add(temp);

我有案例1-45和默认情况。如果可能的话,我想简化一下。谢谢!

6 个答案:

答案 0 :(得分:3)

wordsByLen[temp.length()].add(temp); ---这应该是我猜的。

答案 1 :(得分:3)

不要打扰switch,只需执行

wordsByLen[temp.length() - 1].add(temp)

答案 2 :(得分:3)

String temp;
Scanner sc = new Scanner(str);
while(sc.hasNext())
{
    temp = sc.next();
    wordsByLen[temp.length()-1].add(temp);
}

答案 3 :(得分:2)

只使用比长度短的

int len = temp.length();
wordsByLen[len - 1].add(temp);

答案 4 :(得分:2)

为什么你需要在这里使用开关盒。试试这个:

String temp;
        Scanner sc = new Scanner(str);
        while(sc.hasNext())
        {
            temp = sc.next();
          if(temp.length > 0) {
            wordsByLen[temp.length()-1].add(temp)

        }

答案 5 :(得分:1)

您可以直接使用以下内容代替切换:

wordsByLen[temp.length()-1].add(temp);