【问题标题】:Why can I not take the substring of this string?为什么我不能取这个字符串的子字符串?
【发布时间】:2015-07-16 14:35:16
【问题描述】:

从此功能代码,

String line = "";
    int i = 0;
    while (line != null) {
        line = br.readLine();
        checklistList.add(fillList("list", line));
        i++;
    }

该行类似于 checklist(date).txt,我希望它只是日期。对我来说显而易见的解决方案是

String line = "";
    int i = 0;
    while (line != null) {
        line = br.readLine();
        checklistList.add(fillList("list", line.substring(13, 29)));
        i++;
    }

但是这会导致错误:

Attempt to invoke virtual method 'java.lang.String java.lang.String.substring(int, int)' on a null object reference

可以做些什么来解决这个问题?如果有影响,可以在 android 上运行。

【问题讨论】:

  • .. on a null object reference .. 可能迭代已经到达文件末尾,此时行变量为null。它在错误语句中说对象是null

标签: java android string nullpointerexception


【解决方案1】:

在尝试对其进行子字符串化之前,您必须检查 line 是否为 null。

String line = "";
int i = 0;
while (line != null) {
    line = br.readLine();    
    if (line != null) {    // CHeck if line is null or not
        checklistList.add(fillList("list", line.substring(13, 29)));
    }
    i++;
}

注意:我不知道您的代码的任何其他详细信息,但也许您还必须检查该行是否足够长以在您指定的位置对其进行子串化。

【讨论】:

  • 或者只是将 readLine() 移动到循环中,例如 while((line = br.readLine()) != null)
  • @COdebender 是的......许多可能的实现是可用的。这仅强调对空值的检查。有点不同的是,在这个解决方案中,我最后一次增加了 1。我不知道意图是不是这个。所以我的代码和你的有区别
【解决方案2】:

正如@David 所说,您需要检查行是否不是null

这是一个标准的方法

String line = "";
int i = 0;
while ((line = br.readLine()) != null) { //set line then check for null
    checklistList.add(fillList("list", line.substring(13, 29)));
    i++;
}

【讨论】:

  • 需要检查字符串的长度以忽略 java.lang.StringIndexOutOfBoundsException: String index out of range
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
  • 2012-06-20
  • 2020-09-25
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
相关资源
最近更新 更多