当我键入1 1时,它将用H代替1 1中的N。 我该如何更换? 当我输入1时,我有读者x和Y,然后再输入1,它将用H替换N
String[][] board = {
{ "N", "N", "N", "N", "N" },
{ "N", "N", "N", "N", "N" },
{ "N", "N", "N", "N", "N" },
{ "N", "N", "N", "N", "N" },
{ "N", "N", "N", "N", "N" }
};
for (int i = 0; i < board.length; i++) {
System.out.print(board.length - i + " ");
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
if(i == board.length - 1) {
System.out.println("");
System.out.print(" ");
for(int k = 1; k < board[i].length + 1; k++) {
System.out.print(" " + k);
}
}
System.out.println("");
}
System.out.print("Please enter position X: ");
Scanner inputx = new Scanner(System.in);
int readerx = inputx.nextInt();
System.out.print("Please enter position Y: ");
Scanner inputy = new Scanner(System.in);
int readery = inputy.nextInt();
/*replace board[readerx - 1][readery - 1] with H*/
答案 0 :(得分:1)
我编写了代码,但是从输出中看到的是您可能错误地对数组索引进行了编号。垂直按5 4 3 2 1顺序打印。如果您故意这样做,那么您可以共享所需的输出,那么我就可以更改答案。
如下更改代码:
public class Main {
public static void main(String[] args) throws IOException {
String[][] board = {
{ "N", "N", "N", "N", "N" },
{ "N", "N", "N", "N", "N" },
{ "N", "N", "N", "N", "N" },
{ "N", "N", "N", "N", "N" },
{ "N", "N", "N", "N", "N" }
};
printArray(board);
System.out.print("Please enter position X: ");
Scanner inputx = new Scanner(System.in);
int readerx = inputx.nextInt();
System.out.print("Please enter position Y: ");
Scanner inputy = new Scanner(System.in);
int readery = inputy.nextInt();
board[readerx][readery] = "H";
printArray(board);
}
private static void printArray(String[][] board) {
for (int i = 0; i < board.length; i++) {
System.out.print(board.length - i + " ");
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
if(i == board.length - 1) {
System.out.println("");
System.out.print(" ");
for(int k = 1; k < board[i].length + 1; k++) {
System.out.print(" " + k);
}
}
System.out.println("");
}
}
}
输出为:
5 N N N N N
4 N N N N N
3 N N N N N
2 N N N N N
1 N N N N N
1 2 3 4 5
Please enter position X: 1
Please enter position Y: 1
5 N N N N N
4 N H N N N // here it changed
3 N N N N N
2 N N N N N
1 N N N N N
1 2 3 4 5
编辑:如果您希望当前的索引顺序,则应使用下面的补货代码,该代码首先计算目标数组:
int targetArray = board.length - readerx;
board[targetArray][readery - 1] = "H";