import java.util.Random;
import java.util.Scanner;
public class MineSweeper {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
boolean playAgain = true;
System.out.println("Welcome to Mine Sweeper!");
while (playAgain) {
final int MIN_SIZE = 3;
final int MAX_SIZE = 20;
final char NO_NEARBY_MINE = ' ';
String errorWidth = "Expected a number from " + MIN_SIZE + " to " + MAX_SIZE + "\nWhat width of map would you like (" + MIN_SIZE + "-" + MAX_SIZE + "):";
String errorHeight = "Expected a number from " + MIN_SIZE + " to " + MAX_SIZE + "\nWhat height of map would you like (" + MIN_SIZE + "-" + MAX_SIZE + "):";
System.out.println("What width of map would you like (" + MIN_SIZE + "-" + MAX_SIZE + "):");
int userWidth = promptUser(scnr, errorWidth, MIN_SIZE, MAX_SIZE);
System.out.println("What height of map would you like (" + MIN_SIZE + "-" + MAX_SIZE + "):");
int userHeight = promptUser(scnr, errorHeight, MIN_SIZE, MAX_SIZE);
String errorGetRow = "Expected a number from " + 1 + " to " + userWidth + ".";
String errorGetCol = "Expected a number from " + 1 + " to " + userHeight + ".";
int minRowCol = 1;
char[][] mineArray = new char[userHeight][userWidth];
eraseMap(mineArray);
simplePrintMap(mineArray);
System.out.println("row: ");
int row = promptUser(scnr, errorGetRow, minRowCol, userWidth);
System.out.println("column: ");
int column = promptUser(scnr, errorGetCol, minRowCol, userHeight);
mineArray[row-1][column-1] = NO_NEARBY_MINE;
simplePrintMap(mineArray);
System.out.println("Would you like to play again (y/n)?");
String response = scnr.next();
if (response.startsWith("Y") || response.startsWith("y")) {
playAgain = true;
}
else {
playAgain = false;
}
}
System.out.println("Thank you for playing Mine Sweeper!");
}
public static int promptUser(Scanner in, String prompt, int min, int max) {
int userTempVal = 0;
do {
userTempVal = in.nextInt();
if (userTempVal < min || userTempVal > max) {
System.out.println(prompt);
}
}while (userTempVal < min || userTempVal > max);
return userTempVal;
}
public static void eraseMap(char[][] map) {
final char UNSWEPT = '.';
for (int row = 0; row < map.length; row++) {
for (int col = 0; col < map[row].length; col++) {
map[row][col] = UNSWEPT;
}
}
return;
}
public static void simplePrintMap(char[][] map) {
for (int row = 0; row < map.length; row++) {
for (int col = 0; col < map[row].length; col++) {
System.out.print(map[row][col] + " ");
}
System.out.println("");
}
return; //FIXME
}
编辑:所以我将代码更改为使用 .equals 而不是 ==,当我输入一个只有一个单词的字符串时,我的代码可以成功运行,所以“是”。如果我输入一个包含多个单词的字符串(“是的,我愿意”),我仍然会收到错误消息。键入包含多个单词的字符串会产生错误。当我使用 scnr 时。next(),它总是编译 else 语句,即使语句是“Yes I do”,其中第一个字母是 Y。如果我使用 scnr 。nextLine() 它编译 if 语句,重新启动循环,打印“地图的宽度...”,然后在我输入任何内容之前给出错误。
我主要指的是底部的main方法,从“Would you like to play again”到main方法的末尾。我的 promptUser 方法也有问题,如果用户输入除 int 之外的任何内容,我希望该方法显示错误消息并再次扫描 int。