这是代码
public void promptUser(){
Scanner scan = new Scanner(System.in);
System.out.print("Pick a coordinate [row col] or press [q] to quit.");
int row = 0;
int row = 0;
String line = scan.nextLine().trim();
String[] contents = line.split(" ");
if (contents[0] == "q"){
isRunning = false;
System.exit(0);
}// if quit
if (contents.length < 1 || contents.length > 2){
System.out.print("Invalid Response. Try again.");
promptUser();
}// if wrong amount of input
else {
row = Integer.parseInt(contents[0]);
col = Integer.parseInt(contents[1]);
}// parse ints else
if (inBounds(row, col) == true){
if(!(board[row][col] == 'c'){
click(row, col);
}// has been clicked
}// in bounds?
else{
System.out.print("Invalid response. Try again.");
promptUser();
}// else error
}// promptUser method
这是错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "q"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:514)
at Minesweeper.promptUser(Minesweeper.java:197)
at Driver.main(Driver.java:12)
此方法旨在从用户那里获取输入,检查它是否有错误。如果它是正确的,那么如果输入“q”则它应该退出程序,如果它是尚未被点击的边界内的两个整数,则“点击”该坐标。如果没有此错误,我无法输入“q”。我也得到一个outOfBounds exception
输入任何整数的值。(是的,这是家庭作业,我已经搜索了很长时间,但还没有完全找到如何解决这个问题。)非常感谢任何和所有的帮助。
这是我使用的 inBounds 方法,以及初始化(板子初始化的地方)
public void initialize(){
isRunning = true;
board = new char[this.rows][this.cols];
for (int i = 0; i < board.length; i++){
for(int j = 0; j < board[i].length; j++){
board[i][j] = 'e';
}
}
mineBoard = new boolean[this.rows][this.cols];
for (int i = 0; i < mineBoard.length; i++){
for (int j = 0; j < mineBoard[i].length; j++){
mineBoard[i][j] = false;
}
}
Random bob = new Random();
Random sally = new Random();
for (int i = mines; i > 0; i--){
int mineX = bob.nextInt(10);
int mineY = sally.nextInt(10);
if (mineBoard[mineX][mineY] == false){
mineBoard[mineX][mineY] = true;
}
else{
i++;
}
}
}
这就是初始化......这里是 inBounds
private boolean inBounds(int row, int col){
if (row < 0 || row > board.length){
return false;
}
if (col < 0 || col > board[0].length){
return false;
}else
return true;
}
还有什么可以帮助的吗?我用 q 解决了这个问题,但我一直遇到越界问题。