如何在此代码中防止或处理java.lang.ArrayIndexOutOfBoundsException?

时间:2019-03-31 18:08:41

标签: java indexoutofboundsexception

我正在使用数组创建电话目录(我必须使用数组)。当我尝试传递仅包含姓氏和首字母(而不是数字)或仅包含姓氏的输入行时,我想抛出IllegalArgumentException。但是,当我尝试对其进行测试时,却抛出了ArrayIndexOutOfBoundsException。

这是一些addEntry方法。

@Override
    public void addEntry(String line) throws IllegalArgumentException{

        int size = entries.length;

        String[] newLine = line.split("\\s+");
        String surname = newLine[0];
        String initials = newLine[1];
        String number = newLine[2];

        if (surname.length()<1 || initials.length()<1 || number.length()<1){
            throw new IllegalArgumentException("Please provide a Surname, Initials and a Number");
        }


        Entry newEntry = new Entry(surname, initials, number);

如果我尝试将以下条目传递给该方法:arrayDirectory.addEntry("Lara AL");

我收到此错误消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

指向此处:String number = newLine[2];

4 个答案:

答案 0 :(得分:0)

如果传递“ Lara AL”作为输入,则newLine数组将被初始化为

["Lara", "AL"]

,长度为2。不必单独检查姓氏,缩写和数字的长度,只需在初始化数组后检查数组的长度是否小于3。

String[] newLine = line.split("\\s+");
if (newLine.length < 3) {
    throw new IllegalArgumentException("Please provide a Surname, Initials and a Number");
}

答案 1 :(得分:0)

我认为你应该这样写

String surname =  newLine.length > 0 ? newLine[0] : "";
String initials = newLine.length > 1 ? newLine[1] : "";
String number = newLine.length > 2 ? newLine[2] : "";

答案 2 :(得分:0)

在分配给变量之前,请检查数组的长度。喜欢:

@Override
    public void addEntry(String line) throws IllegalArgumentException{

        int size = entries.length;

        String[] newLine = line.split("\\s+");
        if(newLine.length < 3)throw new IllegalArgumentException("Please provide a Surname, Initials and a Number");
        String surname = newLine[0];
        String initials = newLine[1];
        String number = newLine[2];

        if (surname.length()< 5 || initials.length()< 5 || number.length()< 5){
            throw new IllegalArgumentException("Please provide a Surname, Initials and a Number that is atleast 5 char long");
       //do other validations here like number -  is it a number or maybe has dashes and spaces

        }


        Entry newEntry = new Entry(surname, initials, number);

答案 3 :(得分:0)

问题正在发生,因为

String[] newLine = line.split("\\s+");

何时

String line = "Lara   AL";

评估为:

String[] newLine = ["Lara", "AL"];

当newLine仅包含2个元素时,您正在尝试访问newLine[2]

之所以会这样,是因为\\s+模式匹配一​​个或多个空格。

为避免这种情况,您可以简单地检查newLine.size() > 2或将正则表达式调整为\\s{1}或简单地" ",这将强制按单个空格及以上的空格进行分割,导致:

String[] newLine = ["Lara", " ", "AL"];