【问题标题】:StringIndexOutOfBoundsException: String index out of range: 0 while reading a file [duplicate]StringIndexOutOfBoundsException:字符串索引超出范围:读取文件时为 0 [重复]
【发布时间】:2014-03-07 16:26:06
【问题描述】:

我有一个读取文件的简单程序。现在行之间有一个空格。我得到 StringIndexOutOfBoundsException: String index out of range: 0 错误。请帮忙

class main{
    public static void main(String args[]) {
       String str;
        try {
    BufferedReader br = new BufferedReader ( new FileReader("train.txt"));
    while((str=br.readLine())!=null){ 
    System.out.println(str);
    int a=str.charAt(0);

    if(str.trim().length()==0){
        System.out.println("stupid");
    }
    else if(a==32){
        System.out.println("ddddd");
    }

    else if(str.charAt(0)=='A' ||str.charAt(0)=='a'){
        System.out.println("hahha");
    }
    else if(str.charAt(0)=='C' ||str.charAt(0)=='c'){
        System.out.println("lol");
    }

    else if(str.charAt(0)=='D' ||str.charAt(0)=='d'){
        System.out.println("rofl");
    }
    else{
    System.out.println("blank");
    }


}
        }
catch (FileNotFoundException e){
    System.out.println(e);
}
catch (IOException e){
    System.out.println(e);
}
    }

【问题讨论】:

  • Arrival Mar 21, 2014 10:30 38472 Super Express Cancel 40003 这是我文件中包含的数据。我的代码无法越过到达线和取消线之间的空白区域
  • 使用堆栈跟踪发布您的异常。

标签: java bufferedreader


【解决方案1】:

如果一行为空,则索引 0 处没有字符,因为字符串为空。你正在执行这一行:

int a=str.charAt(0);

在测试该行是否为空白之前。有几种可能的解决方案。一种是像这样重新组织你的代码:

if(str.trim().length()==0){
    System.out.println("stupid");
    continue; // so rest of loop body is skipped
}
int a=str.charAt(0);
if(a==32){
    System.out.println("ddddd");
}

【讨论】:

  • 感谢大开眼界
【解决方案2】:

下面的行在读取空行时会抛出StringIndexOutOfBoundsException

int a=str.charAt(0);

替换为:

if(str.trim().length()>0)
a=str.charAt(0);

【讨论】:

  • 总是使用大括号。有关如果不这样做会发生什么情况的示例,请查看以下问题:stackoverflow.com/questions/22177675/…
  • 谢谢。我只写了一个声明,这就是我避免使用括号的原因。是的,对于嵌套的 if else 条件,我必须使用括号来确保哪个代码块在哪个条件下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
  • 2013-09-25
  • 2017-01-06
相关资源
最近更新 更多