【问题标题】:Check if String[index] is empty before throwing ArrayIndexOutOfBounds exception在抛出 ArrayIndexOutOfBounds 异常之前检查 String[index] 是否为空
【发布时间】:2019-06-19 19:36:00
【问题描述】:

这可能是一个愚蠢的问题,但我错过了一些东西,只是无法弄清楚是什么......寻找一种合理的方法来检查给定索引是否存在于 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' 只是伪变量名而不是实际变量名

【问题讨论】:

  • 什么是index?是伪代码还是实际变量?
  • @Gendarme 只是伪
  • 第一次检查 if (index<split.length) 怎么样,然后如果 if(split[index] != null)

标签: java arrays string split


【解决方案1】:

数组索引范围从0length-1,并且它们始终存在。只要index >= 0index < split.lengthsplit[index]就不会抛出ArrayIndexOutOfBoundsException

所以只需添加一个 if 语句来检查:

if(index >=0 && index < split.length) {
    [...]
}

【讨论】:

    猜你喜欢
    • 2011-09-21
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2010-12-04
    相关资源
    最近更新 更多