首页 > 解决方案 > 字符串的数组测试

问题描述

这是一个更大项目的一部分,但我遇到了一些相当基本的问题。我不断得到一个数组越界异常。你能告诉我为什么吗?

public class Arrayif {

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ParseException, ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, InterruptedException {

    String[] strarray = new String[0];

    String liveBoA = "test";

    if (strarray[0].isEmpty()) {
        strarray[0] = liveBoA;
        System.out.println("hello");
    } else if (strarray[0].contains(liveBoA)) {

        System.out.println("bellow");

    }
}

}

这也不起作用:

public class Arrayif {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ParseException, ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, InterruptedException {

        String[] strarray = new String[1];

        String liveBoA = "test";

        if (strarray[0].isEmpty()) {
            strarray[0] = liveBoA;
            System.out.println("hello");
        } else if (strarray[0].contains(liveBoA)) {

            System.out.println("bellow");

        }
    }
}

标签: javaarrays

解决方案


String[] strarray = new String[0];将创建空数组。

您需要更改为String[] strarray = new String[1];

或添加strarray.length > 0到 if 条件if (strarray.length > 0 && strarray[0].isEmpty()) 以防止array out of bounds exception

更新:如果你做了初始化数组,它会抛出空指针异常。

String[] strarray = new String[1];
strarray[0] = "Your string";

如果你不想第一次初始化,你应该在使用之前检查 nullisEmpty()并且contains()

public static boolean isNullOrEmpty(String str) {
        return str==null || str.isEmpty();
 }

推荐阅读