I am having trouble solving the minesweepers problem because I am getting an index out of bound and can't figure out why: Here is the link of the problem
I think my code isn't exactly efficient but I just want to solve this , here is the code :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Mine_Sweepers {
public static void main(String [] args) throws IOException
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
//Taking the dimensions of the grid...
StringTokenizer s=new StringTokenizer(bf.readLine());
int b=Integer.parseInt(s.nextToken()), a=Integer.parseInt(s.nextToken());
while(b!=0 && a!=0)
{
mine(b,a);
s=new StringTokenizer(bf.readLine());
b=Integer.parseInt(s.nextToken());
a=Integer.parseInt(s.nextToken());
}
}
public static void mine(int b,int a) throws IOException
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
boolean array_first=false,array_last=false,string_first=false,string_last=false;
String []x=new String[a];
for(int i=0;i<a;i++)
x[i]=bf.readLine();
for(int i=0;i<a;i++)
{
//Here I am checking whether this is the first field in the array or if it is the last
array_first=(i==0)?true:false;
array_last=(i==a-1)?true:false;
for(int j=0; j<b; j++)
{
//Here I am checking whether this is the first char in the String in the array or if it is the last
string_first=(j==0)?true:false;
string_last=(j==a-1)?true:false;
int counter=0;
if(x[i].charAt(j)!='*')
{
if(!string_first)
{
if(x[i].charAt(j-1)=='*')
counter++;
if(!array_first & x[i-1].charAt(j-1)=='*')
counter++;
if(!array_last & x[i+1].charAt(j-1)=='*')
counter++;
}
if(!string_last )
{
if(x[i].charAt(j+1)=='*')
counter++;
if(!array_first && x[i-1].charAt(j+1)=='*')
counter++;
if(!array_last & x[i+1].charAt(j+1)=='*')
counter++;
}
if(!array_first & x[i-1].charAt(j)=='*')
counter++;
if(!array_last & x[i+1].charAt(j)=='*')
counter++;
System.out.print(counter);
}
else
System.out.print('*');
}
System.out.println();
}
}
}