Skip to content
Advertisement

“String.substring(int, int) line: not available” causes error

Somehow my if loop using a substring to check a .txt file is causing problems. Without the if loop, everything works fine. But with it, it seems that an empty line in the text file is causing it to crash. It is working until the first empty line in the file, and then I get this error. What could I do about that?

code:

public class S1_Blockchain extends ConsoleProgram {

    public void init() {
        setSize(400, 250);
        setFont("Arial-bold-18");

        BufferedReader br = null;
        String line;
        
        try {
            br = new BufferedReader(new FileReader("block_chain.txt"));
            while((line = br.readLine()) != null){
                if(line.substring(0,1).equals("T") || line.substring(0,1).equals("G")) {
                   System.out.println(line);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
    }
}

Advertisement

Answer

You might want to also check empty string:

if( !line.trim().isEmpty() && (line.substring(0,1).equals("T") || line.substring(0,1).equals("G"))) { ... }

You then might also want to refactor the code to make it more readable:

public class S1_Blockchain extends ConsoleProgram {

    public void init() {
        setSize(400, 250);
        setFont("Arial-bold-18");

        BufferedReader br = null;
        String line;
        
        try {
            br = new BufferedReader(new FileReader("block_chain.txt"));
            while((line = br.readLine()) != null){
                if(shouldConsider(line)) {
                   System.out.println(line);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
    }
}

private boolean shouldConsider(String line){
  return !line.trim().isEmpty() 
         && 
         (line.substring(0,1).equals("T") || line.substring(0,1).equals("G"));
}
7 People found this is helpful
Advertisement