java - 字符串的数组测试
问题描述
这是一个更大项目的一部分,但我遇到了一些相当基本的问题。我不断得到一个数组越界异常。你能告诉我为什么吗?
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 = 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();
}
推荐阅读
- c# - 如何将类传递给方法参数是泛型的方法
- javascript - 如何从 Instagram 媒体轮播相册返回视频?
- domain-driven-design - 我应该避免在没有事件存储的系统中使用聚合 (DDD) 吗?
- python - 有没有办法从 CSS 选择器中获取特定文本?
- python - 使用 Redis 时,Celery 中可靠的任务处理需要什么?
- c++ - 编译错误:变量的类型不完整
- python - Django 休息框架 - 没有这样的表
- ludwig - Ludwig 何时使用 SET 功能、SEQUENCE 功能、两者的示例数据
- javascript - 数组过滤器在 Reactjs 中返回一个空数组
- javascript - 使用 selenium 在 javascript 中解析数据