-1

I wrote a code for minesweeper problem. It creates an MxN minesweeper game where each cell is a bomb with probability p. Prints out the m-by-n game and the neighboring bomb counts. Code:

class Minesweeper { 
    public static void main(String[] args) { 
        int m = Integer.parseInt(args[0]);
        int n = Integer.parseInt(args[1]);
        double p = Double.parseDouble(args[2]);

    try {
        boolean[][] bombs = new boolean[m+2][n+2];
        for (int i = 1; i <= m; i++)
            for (int j = 1; j <= n; j++)
                bombs[i][j] = (Math.random() < p);


        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++)
                if (bombs[i][j]) System.out.print("* ");
                else             System.out.print(". ");
            System.out.println();
        }


        int[][] sol = new int[m+2][n+2];
        for (int i = 1; i <= m; i++)
            for (int j = 1; j <= n; j++)
                // (ii, jj) indexes neighboring cells
                for (int ii = i - 1; ii <= i + 1; ii++)
                    for (int jj = j - 1; jj <= j + 1; jj++)
                        if (bombs[ii][jj]) sol[i][j]++;


        System.out.println();
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (bombs[i][j]) System.out.print("* ");
                else             System.out.print(sol[i][j] + " ");
            }
            System.out.println();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    }
}  

Do I need to give any condition after parsing?

int m = Integer.parseInt(args[0]);
int n = Integer.parseInt(args[1]);
double p = Double.parseDouble(args[2]);  

Please help me.

Ajay Kulkarni
  • 2,900
  • 13
  • 48
  • 97
  • 3
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – SomeJavaGuy Jan 30 '17 at 06:53

1 Answers1

1

Just give a extra condition before parsing the argument.

if (args.length >= 3) {
    m = Integer.parseInt(args[0]);
    n = Integer.parseInt(args[1]);
    p = Double.parseDouble(args[2]);
}
Masum
  • 401
  • 3
  • 14