字符串的数组测试

时间:2019-04-27 10:23:51

标签: java arrays

这是一个较大项目的一部分,但是我在一些相当基本的问题上遇到了问题。我不断获取数组超出范围的异常。你能告诉我为什么吗?

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");

        }
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

或在条件为strarray.length > 0的情况下添加if (strarray.length > 0 && strarray[0].isEmpty()) 防止array out of bounds exception

更新:如果您执行了初始化数组,则会抛出空指针异常。

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

如果您不想第一次初始化,则应在isEmpty()contains()之前使用null进行检查

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