0

我正在尝试从可能具有不同字数的文本文件中读取命令。我正在尝试使用 IF 语句,以免数组越界异常。谁能告诉我我做错了什么?谢谢你。这是它发生的代码部分。

    read = new Scanner(new File("Phone.txt"));

    //this will loop thru file until end of file
    while (read.hasNext())
    {

    whole = read.nextLine().trim();
    String[] tokens = whole.split(" ");//array to split up line
    command = tokens[0].toLowerCase();//all lines will have at least one word
    if (tokens.length > 0)//if more than one word, 2nd will be name
    {
        name1st.setFirst(tokens[1]);
    }

    if (tokens.length > 1)//if more than one word, 3rd will be phone #
    {
        phone = tokens[2];
    }
        switch (command)
        {
            case "add":
                nameList.add(name1st, phone);
                break;
            case "locate":
                nameList.getValue(name1st);
                break;
            case "remove":
                    nameList.remove(name1st);
                break;
            case "print":
                    nameList.display();
        }//end switch

    }//end while
4

2 回答 2

0

数组索引从 0 开始。并且数组的长度等于数组中元素的数量。

    if (tokens.length > 1)//if more than one word, 2nd will be name
    {
        name1st.setFirst(tokens[1]);
    }

    if (tokens.length > 2)//if more than one word, 3rd will be phone #
    {
        phone = tokens[2];
    }

您可以如上所述更正您的代码。

于 2013-04-08T03:30:46.303 回答
0

好的,

弄清楚了。长度与索引不同。如果它的 idex 为 0,它的长度为 1,所以我必须将 if 中的条件提高 1。然后它运行了。感谢所有为此工作的人

于 2013-04-08T03:33:01.933 回答