我为扫雷问题编写了一个代码。它创建了一个MxN扫雷游戏,其中每个细胞都是概率为p的炸弹。打印m-by-n游戏和邻近的炸弹计数。
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();
}
}
}
解析后我需要提供任何条件吗?
int m = Integer.parseInt(args[0]);
int n = Integer.parseInt(args[1]);
double p = Double.parseDouble(args[2]);
请帮帮我。
答案 0 :(得分:1)
在解析参数之前给出一个额外的条件。
if (args.length >= 3) {
m = Integer.parseInt(args[0]);
n = Integer.parseInt(args[1]);
p = Double.parseDouble(args[2]);
}