-1

I want to print at the output of a table that stars for the bombs and in other houses to show the number of bombs in the eight houses around the house. gives java.lang.ArrayIndexOutOfBoundsException in the line marked with a comment. What is the problem? For example with the following input:

4 3  //Table Dimensions
5    //Number of bombs
1 1 //The position of the bombs
4 2
1 3
3 2
4 3

I expect this output

* 2 *
2 3 2
2 * 3
2 * *

my code:

import java.util.*;
public class Main { 

   public static void main(String args[]) {
        Scanner sc=new Scanner(System.in);
     int a;
int b;
int c;
a =sc.nextInt();
 b=sc.nextInt();
 c=sc.nextInt();

  int s[][] = new int [c][2]  ;
 char s1[][]=new char [a][b];
    for(int i=0;i<c;i++){
         for(int j=0;j<2;j++){
       s[i][j]=sc.nextInt();
         }
          s1[(s[i][0])-1][(s[i][1])-1]='*';  
    }
for(int i=0;i<a;i++){
         for(int j=0;j<b;j++){
             if(s1[i][j]!='*')s1[i][j]='0';
         }}
for(int i=0;i<a;i++){
         for(int j=0;j<b;j++){
       for(int h=i-1;h<i+2;h++){
             for(int g=j-1;g<j+2;g++){
                if(h<a && g<b){
                    if(s1[h][g]=='*')  s1[i][j]++; //this line

                }

             }

       }
         }
    }
    for(int i=0;i<b;i++){
         for(int j=0;j<a;j++){
              System.out.print(s1[j][i]+" ");
         }
        System.out.print('\n');
    }

 }

       }

  • Why don't you just print out the values of h, g, i, and j, work out which are invalid indexes for s1 and then try to understand how your code got to the point it's using invalid indexes? – jarmod Mar 01 '20 at 16:50
  • I am checking the condition in the previous line so it should not enter this block but it will come in and cause trouble – Zahra Ghanbari Mar 01 '20 at 16:58
  • I doubt the JRE is incorrectly throwing ArrayIndexOutOfBoundsException so one or more assumptions you are making are likely incorrect. – jarmod Mar 01 '20 at 17:02

1 Answers1

1

h= -1 & g= -1 at mentioned line.

That is why the java.lang.ArrayIndexOutOfBoundsException

And, same reason, why it passed your condtion of if(h<a && g<b)

Aditya Rewari
  • 2,343
  • 2
  • 23
  • 36