-1

I have written this code to find the common prefix for 3 Strings. However, it gives outOfBond Exception in the 14.line ( in the first while statement ). Could you please help to solve this problem?

import java.util.*;

public class Main{
public static void main (String[] args){
Scanner scanner = new Scanner(System.in);

    String str1 = scanner.next();
    String str2 = scanner.next();
    String str3 = scanner.next();

    int i = 0;
    int j = 0;

    while (Character.compare(str1.charAt(i), str2.charAt(i))  == 0){
            i++;
    }

    String subStr1 = str1.substring(0,i);

    while (Character.compare(subStr1.charAt(j), str3.charAt(j))  == 0){
            j++;
    }

    String subStr2 = subStr1.substring(0,j);

    System.out.println(subStr2);



  }}

1 Answers1

0
    while (Character.compare(str1.charAt(i), str2.charAt(i))  == 0){
            i++;
    }

Here, you increment i while corresponding characters from str1 and str2 are equal. If str1 is equal to str2 or str1 is substring of str2 or str2 is substring of str1 then i is incremented until i is greater, than str1 or str2.

And then exception is thrown, because charAt(i) tries to get a character, which index is greater, than string length.

Ilya Sazonov
  • 888
  • 8
  • 13