拆分方法抛出IndexOutOfBounds异常

时间:2019-03-24 23:19:22

标签: java split indexoutofboundsexception

我正在尝试使用数组来建立电话目录(我必须使用数组)。我正在尝试编写添加新条目的方法。我决定添加一行新条目,该行将使用::方法分为三个部分(姓,缩写,数字)和制表符。当我尝试对该方法进行测试时,我抛出了split

这是IndexOutOfBoundsException方法

addEntry

这是我尝试添加的条目:

@Override
public void addEntry(String line) {

    String[] entryLine = line.split("\\t");
    String surname = entryLine[0];
    String initial = entryLine[1];
    String number = entryLine[2];

    Entry entry = new Entry(surname, initial, number);
    count++;

    if (surname == null || initial == null || number == null) {
        throw new IllegalArgumentException("Please fill all the required fields, [surname,initials,number]");
    }
    if (count == entries.length) {
        Entry[] tempEntries = new Entry[2 * count];
        System.arraycopy(entries, 0, tempEntries, 0, count);
        entries = tempEntries;
    } else {
        int size = entries.length;
        for (int i = 0; i < size - 1; i++) {
            for (int j = i + 1; j < entries.length; j++) {
                String one = entry.getSurname();

                if (one.toLowerCase().compareTo(surname.toLowerCase()) > 0) {
                    Entry tempE = entries[i];
                    entries[i] = entries[j];
                    entries[j] = tempE;
                }
            }

        }
    }
}

2 个答案:

答案 0 :(得分:2)

如果您输入的String确实是

Smith  SK  005598

然后使用拆分正则表达式

\\t

(tab)无法工作,因为片段之间没有制表符分隔。
相反,您需要使用

line.split("\\s+");

由于\s+将匹配任意数量的空格。
输出将正确导致

[Smith, SK, 005598]

要使用标签将每个部分分开,请使用

Smith\tSK\t005598

只有原始的正则表达式才能起作用。

答案 1 :(得分:1)

没有逻辑:

if (surname == null || initial == null || number == null) 
{
    throw new IllegalArgumentException("Please fill all the required fields, [surname,initials,number]");
}

您应该检查分割线的长度为3:

String[] entryLine = line.split("\\s+");
if (entryLine.length() != 3) 
{
    throw new IllegalArgumentException("...");
}

由于这些变量不会为null,因此对数组的访问将导致IOOB错误。

还应该放

 Entry entry = new Entry(surname, initial, number);
    count++;

在大小检查之后(最好将所有前提条件检查放在方法的开头)。