1

Getting exception in the code below:

import java.io.*;

public static void main(String[] args) throws IOException{
    FileReader objRead = new FileReader("/home/acer/Desktop/sulabh");
    BufferedReader objB = new BufferedReader(objRead);
    String input = null;
    while((input=objB.readLine())!= null){
        String temp = input.substring(0,2);
       if(temp.contains("77")) {
           System.out.println(input);
       }
    }
    objB.close();
}

And error with the answer is:
777
777

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 2, length 0 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319) at java.base/java.lang.String.substring(String.java:1874) at Main.main(Main.java:10)
seenukarthi
  • 8,241
  • 10
  • 47
  • 68

2 Answers2

0

From the java docs for substring:

Throws:
    IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Your String temp = input.substring(0,2); is getting a line shorter than length 2 after it gets the two good lines.

Protect against that as follows.

String temp = "";

if (input.length()>=2){
temp = input.substring(0,2);
}
Jeremy Kahan
  • 3,796
  • 1
  • 10
  • 23
0

I guess the first two lines have been processed fine and it throws error for the blank line at the end. Please check if you have a blank line at the end of the file. The blank line may contain less than 2 chractors.

Alternatively you can try input.startsWith("77") as well

Arun Kamalanathan
  • 8,107
  • 4
  • 23
  • 39