你的代码逻辑基本是对的,但是结构很混乱,你应该把一个大问题拆分为很多小问题,分别解决,就会很清晰了,我按你的思路改了程序,但是你那个point我没弄明白,如果99次之后怎么办不是很明确,所以我干脆无视了public class RandomInt {
private static int[] randomNumArray = null;
private static int[][] box = null;
// record how many numbers has been put into the box
private static int count;
private static void initRandomArray() {
randomNumArray = new int[100];
for (int i = 0; i < 100; i++) {
randomNumArray[i] = (int) (Math.random() * 9 + 1);
}
}
private static void initBox(Scanner scan) {
box = new int[3][3];
while (count < 9) {
System.out.println("You are choosing a location for the random number: " + randomNumArray[count]);
int row;
do {
System.out.println("Please input a row number: (from 0 to 2)");
row = scan.nextInt();
} while (!checkRowAvailable(row));
int column;
do {
System.out.println("Please input a column number: (from 0 to 2)");
column = scan.nextInt();
} while (!checkColumnAvailable(column));
if (checkPutAvailable(row, column)) {
box[row][column] = randomNumArray[count];
System.out.println("You have put a random number at the location of row: " + row + ", column: " + column);
printBox();
count++;
}
}
}
private static boolean checkRowAvailable(int row) {
if (row < 0 || row > 2) {
System.out.println("It should be a legal row number. (from 0 to 2)");
return false;
}
return true;
}
private static boolean checkColumnAvailable(int column) {
if (column < 0 || column > 2) {
System.out.println("It should be a legal column number. (from 0 to 2)");
return false;
}
return true;
}
private static boolean checkPutAvailable(int row, int column) {
if (box[row][column] != 0) {
System.out.println("The location you chose has been occupied already, please ipnut again.");
return false;
}
return true;
}
private static void printBox() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(box[i][j]);
if (j < 2) {
System.out.print(" | ");
}
}
System.out.println();
}
}
private static void playGame(Scanner scan) {
count = 0;
initRandomArray();
initBox(scan);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
playGame(scan);
while (true) {
System.out.println("nDo you want to continue? (y/n)");
String s = scan.next();
if ("y".equalsIgnoreCase(s)) {
System.out.println();
playGame(scan);
} else if ("n".equalsIgnoreCase(s)) {
System.out.println("Good Bye!");
break;
}
}
scan.close();
}
}