简体   繁体   中英

Don't know why the array out of bounds exception occurs

This is the question i tried to solve: Save the string “WELCOMETOZOHOCORPORATION” in a two dimensional array and search for substring like “too” in the two dimensional string both from left to right and from top to bottom.

WELCO/n METOZ/n OHOCO/n RPORA/n TION
Here the /n is used to indicate the nextline And print the start and ending index as

Start index : <1,2>

End index: <3, 2> But i don't know why the error is occurring.!

public class Try1 {
public static void main(String[] args) {
       Scanner sc= new Scanner (System.in);
        System.out.println("Enter the string");
        String str=sc.next();
        char arr[][]=new char[5][5];
        char a[]=str.toCharArray();
        int l=a.length;
        int k=0,flag=0;
        for(int i=0;i<5;i++){
            for(int j=0;j<5;j++){
                if(k!=l){
                arr[i][j]=a[k];
                k++;}else{
                    break;
                }
            }
        }
        for(int i=0;i<5;i++){
            for(int j=0;j<5;j++){
                System.out.print(arr[i][j]+"  ");
            }
            System.out.println();
        }
        System.out.println("Enter the string to search");
        String str1=sc.next();
        char b[]=str1.toCharArray();
        int l1=b.length,y=0,count=0,rl=0,td=0,v=l1-1;
        for(int i=0;i<5;i++){
            for(int j=0;j<5;j++){
                if(arr[i][j]==b[y])//THIS IS THE LINE WHERE THE ERROR OCCURS
                {
                    count++;
                    for(y=1;y<l1;y++){
                        if(arr[i][j+y]==b[y]){
                            rl=count+rl;
                            if(rl==l1){
                                flag=1;
                                System.out.println("Start Index: "+i+","+j);
                                System.out.println("End Index: "+i+","+(j+v));
                                break;
                            }
                        }else if(arr[i+y][j]==b[y]){
                            td=count+td;
                            if(td==l1){
                                flag=1;
                                System.out.println("Start Index: "+i+","+j);
                                System.out.println("End Index: "+(i+v)+","+j);
                                break;
                            }
                        }
                    }
                }
            }
        }
        if(flag==0){
            System.out.println("Not Found");
        }
    }
The error i am facing is,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at try1.Try1.main(Try1.java:48)
Could you help me guys.
                if(arr[i][j]==b[y])//THIS IS THE LINE WHERE THE ERROR OCCURS

The problem is with b[y] . The first time through the loop y is 0, no problem. A few lines later in an inner loop you do

                    for(y=1;y<l1;y++){

This loop leaves y equal to l1 , the length of the word searched for (3 in the case of TOO ). So the second time you get to the line where the error occurs, y is 3 in the example, and you are trying to compare to the element at index 3 in an array of length 3. This causes the exception (as you know, array indices are 0-based, so the valid indices in the array are 0, 1, and 2).

I haven't understood how your code was supposed to work, so hesitate to suggest a fix. If appropriate, you may set y back to 0 for each iteration of the outer loop.

You are getting the error because the maximum index in the array, b for the string TOO is 2 while you are trying to access an element beyond the index 2 .

Do it as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the string: ");
        String str = sc.next();
        char arr[][] = new char[5][5];
        char a[] = str.toCharArray();
        int l = a.length;
        int k = 0;
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (k != l) {
                    arr[i][j] = a[k];
                    k++;
                } else {
                    break;
                }
            }
        }
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print(arr[i][j] + "  ");
            }
            System.out.println();
        }
        System.out.print("Enter the string to search: ");
        String str1 = sc.next();
        char b[] = str1.toCharArray();
        int i, j, countH = 0, countV = 0;
        boolean found = false;
        for (i = 0; i < 5; i++) {
            countH = countV = 0;
            for (j = 0; j < 5 && countH < b.length && countV < b.length; j++) {
                if (arr[i][j] == b[countH]) {
                    countH++;
                } else if (arr[j][i] == b[countV]) {
                    countV++;
                }
            }
            if (countH == b.length) {
                found = true;
                System.out.println("Found horizontally starting at index " + "[" + (i) + "][" + (j - b.length) + "]");
            }
            if (countV == b.length) {
                found = true;
                System.out.println("Found vertically starting at index " + "[" + (j - b.length) + "][" + i + "]");
            }
        }
        if (!found) {
            System.out.println("Not Found");
        }
    }
}

A sample run:

Enter the string: WELCOMETOZOHOCORPORATION
W  E  L  C  O  
M  E  T  O  Z  
O  H  O  C  O  
R  P  O  R  A  
T  I  O  N    
Enter the string to search: TOO
Found vertically starting at index [1][2]

Another sample run:

Enter the string: WELCOMETOZOHOCORPORATION
W  E  L  C  O  
M  E  T  O  Z  
O  H  O  C  O  
R  P  O  R  A  
T  I  O  N   
Enter the string to search: ABC
Not Found

Another sample run:

Enter the string: WELCOMETOZOHOCORPORATION
W  E  L  C  O  
M  E  T  O  Z  
O  H  O  C  O  
R  P  O  R  A  
T  I  O  N    
Enter the string to search: ZOA
Found vertically starting at index [1][4]

Another sample run:

Enter the string: WELCOMETOZOHOCORPORATION
W  E  L  C  O  
M  E  T  O  Z  
O  H  O  C  O  
R  P  O  R  A  
T  I  O  N    
Enter the string to search: MET
Found horizontally starting at index [1][0]

Another sample run:

Enter the string: WELCOMETOZOHOCORPORATION
W  E  L  C  O  
M  E  T  O  Z  
O  H  O  C  O  
R  P  O  R  A  
T  I  O  N    
Enter the string to search: PORA
Found horizontally starting at index [3][1]

Another sample run:

Enter the string: WELCOMETOZOHOCORPORATION
W  E  L  C  O  
M  E  T  O  Z  
O  H  O  C  O  
R  P  O  R  A  
T  I  O  N    
Enter the string to search: PORB
Not Found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM