我正在尝试使用数组做一个电话簿(我必须使用数组)。我正在尝试编写添加新条目的方法。我决定添加一个新条目,其中一行将使用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;
}
}
}
}
}
这是我试图添加的条目:
arrayDirectory.addEntry("Smith SK 005598");
如果你输入的String
真的
Smith SK 005598
然后你的分裂正则表达式
\\t
(制表符)无法正常工作,因为片段未被制表符分隔。 相反,你需要使用
line.split("\\s+");
因为\s+
将匹配任意数量的空格。
输出将正确导致
[Smith, SK, 005598]
要用标签分隔每个部分,你可以使用
Smith\tSK\t005598
只有这样你的原始正则表达式才会起作用。
而不是有逻辑:
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++;
在大小检查之后(最好在方法的开头放置所有前置条件检查)。