Java StringIndexOutOfBoundsException:读取文件时字符串索引超出范围:0

Java StringIndexOutOfBoundsException:读取文件时字符串索引超出范围:0,java,bufferedreader,Java,Bufferedreader,我有一个读取文件的简单程序。现在在这两行之间有一个空格。我得到StringIndexOutOfBoundsException:字符串索引超出范围:0错误。请帮忙 class main{ public static void main(String args[]) { String str; try { BufferedReader br = new BufferedReader ( new FileReader("train.txt"));

我有一个读取文件的简单程序。现在在这两行之间有一个空格。我得到StringIndexOutOfBoundsException:字符串索引超出范围: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);
}
    }

如果一行为空,则索引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");
}

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

int a=str.charAt(0);
替换为:

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

抵达2014年3月21日10:30 38472 Super Express Cancel 40003这是我的文件包含的数据。我的代码无法通过空格,这是在到达和取消LIPEST之间的空白。举个例子说明如果你不这样做会发生什么,看看这个问题:谢谢。我只写了一句话,这就是为什么我避免使用括号。是的,对于嵌套的if-else条件,我必须使用括号来确保在哪个条件下使用哪个代码块。谢谢你的帮助