-3

I have a simple program which reads a file. Now there is a blank space in between the line. I get the StringIndexOutOfBoundsException: String index out of range: 0 error there. Please help

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);
}
    }
Sidarth
  • 1
  • 1
  • 5
  • Arrival Mar 21, 2014 10:30 38472 Super Express Cancel 40003 this is the data that my file contains. My code is unable to get past the blank space which is in between arrival and cancel line – Sidarth Mar 07 '14 at 16:26
  • 1
    Post your exception with the stack trace. – PM 77-1 Mar 07 '14 at 16:28

2 Answers2

3

If a line is blank, there is no character at index 0 since the string is empty. You are executing this line:

int a=str.charAt(0);

before testing whether the line is blank. There are several possible solutions. One is to reorganize your code like this:

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");
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

The line below will throw a StringIndexOutOfBoundsException when it reads an empty line.

int a=str.charAt(0);

Replace it with:

if(str.trim().length()>0)
a=str.charAt(0);
The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
java seeker
  • 1,246
  • 10
  • 13
  • _Always_ use braces. For an example of what can happen if you don't, look at this question: http://stackoverflow.com/questions/22177675/else-statement-is-a-syntax-error – The Guy with The Hat Mar 07 '14 at 17:13
  • thanks.i just written a single statement that's why i avoided brackets. yes, for nested if else condition i must use brackets to ensure which code block under which condition. – java seeker Mar 07 '14 at 17:32