Java 字符串的数组测试

Java 字符串的数组测试,java,arrays,Java,Arrays,这是一个更大的项目的一部分,但我有一个相当基本的问题。我总是得到一个数组超出边界的异常。你能告诉我为什么吗 public class Arrayif { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ParseException, ClassNotFoundException, InstantiationException, Illeg

这是一个更大的项目的一部分,但我有一个相当基本的问题。我总是得到一个数组超出边界的异常。你能告诉我为什么吗

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

        }
    }
}
String[]strarray=新字符串[0];将创建空数组

您需要更改为字符串[]strarray=新字符串[1]

或者在strarray.length>0&&strarray[0]为空时,将strarray.length>0添加到if条件 防止数组越界异常的步骤

更新:如果您使用init数组,则会引发空指针异常

String[] strarray = new String[1];
strarray[0] = "Your string";
如果您不想在第一次初始化,那么在使用isEmpty和contains之前,应该先检查null


数组的长度为零。它没有任何元素的空间。这意味着[0]超出了数组的边界。Buyt这也会导致空点异常,公共类Arrayif{public static void mainString[]args{String[]strarray=new String[1];String liveBoA=test;if strarray[0]。isEmpty{strarray[0]=liveBoA;System.out.printlnhhello;}否则,如果strarray[0].containsliveBoA{System.out.printlnbellow;}}}},则需要初始化数组以将其用作更新的应答,但我的目标是创建一个数组。测试数组中的位置是否包含该值,如果该值为空,则将其放入索引位置的字符串中。由于第二次在计划循环上运行,它将直接转到else if部分。我希望它从空开始,然后填充。你能提出建议吗?你把数组和数组中的内容搞混了。array=新字符串[1]是一个包含一个未填充插槽的数组。按数组[0]=新字符串填充。在填充之前,数组[0]==null。@hiennguen ifstr!=空&!str.isEmpty返回false;返回true;可以缩短为返回str==null | | str.isEmpty;哪一个更适合isNullOrEmpty描述:
public static boolean isNullOrEmpty(String str) {
        return str==null || str.isEmpty();
 }