【问题标题】:Split method throwing an IndexOutOfBounds Exception抛出 IndexOutOfBounds 异常的拆分方法
【发布时间】:2019-03-24 23:19:21
【问题描述】:

我正在尝试使用数组制作电话簿(我必须使用数组)。我正在尝试编写添加新条目的方法。我决定添加一个新条目,其中一行将使用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");

【问题讨论】:

标签: java split indexoutofboundsexception


【解决方案1】:

如果您输入的String 是真的

Smith  SK  005598

然后你的分裂正则表达式

\\t

(制表符)不能工作,因为这些片段没有被制表符分隔。
相反,您需要使用

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

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

[Smith, SK, 005598]

要让每个部分都用制表符分隔,您可以使用

Smith\tSK\t005598

只有这样你原来的正则表达式才会起作用。

【讨论】:

  • 或者如果你只是想在标签上拆分,去: line.split("\t") 加倍 '\\' 将转义 '\'
  • @BillNaylor 是的。此外,他现在使用的版本“\\t”也可以正常工作,但前提是使用“\t”分隔片段,正如我所写的那样。
【解决方案2】:

而不是有逻辑:

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("...");
}

因为这些变量不会为空,所以数组访问会导致IOOB错误。

你也应该放

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

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

【讨论】:

    猜你喜欢
    • 2013-08-01
    • 2014-05-10
    • 2014-04-03
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    相关资源
    最近更新 更多