这可能是一个愚蠢的问题,但我错过了一些东西,只是无法弄清楚什么...寻找一种明智的方法来检查给定索引是否存在于 String[]
数组
字符串是 K,V 对的表示,但有时 V 可能为空,因此可能的字符串示例是:
Foo1:Bla1
Foo2:Bla2
Foo3:
Foo4:Bla4
public void constructPair(String string) {
String[] split = string.split(":");
...
if(split[index] != null) { } // nope
if(!split[index].isEmpty() || !split[index].isBlank() { } //nope
if(split[index].length() > 1) { } // nope
...
}
或者我应该将整个事情包装在 try {} catch() {}
中吗?阻止并相应地处理异常?
编辑:为了清楚起见,'index'
只是伪变量而不是实际变量名称
最佳答案
数组索引范围为 0
至length-1
,并且它们始终存在。只要index >= 0
和index < split.length
, split[index]
不会抛出ArrayIndexOutOfBoundsException
.
因此只需添加一个 if 语句来检查这一点:
if(index >=0 && index < split.length) {
[...]
}
关于java - 在抛出 ArrayIndexOutOfBounds 异常之前检查 String[index] 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54374226/