gpt4 book ai didi

java - 替换数组中的字符串并将其保留在内存中?

转载 作者:行者123 更新时间:2023-12-01 10:50:10 26 4
gpt4 key购买 nike

所以我在完善我的程序时遇到了问题。该程序应该使用用户输入创建一个一维数组。然后它会创建一个像这样的“O”框..

N = 4

OOOO
OOOO
OOOO
OOOO

用户根据框输入坐标,“O”更改为“X”。该程序应该在选择坐标后重复自身,同时记住 X 的位置并将其包含在下一个循环中。

我尝试实现一个 while 循环,但似乎代码只是在数组上循环而不记住 X 的最后位置。

我如何更改代码,使其执行我需要执行的操作?

public static void makeArray(int M) {
String input = "";
boolean repeat = false;
int N = InputNumber(input);
String[] Board = new String[N];
M = (int) Math.sqrt(N);
String A = "O";
String B = "X";

System.out.println("Printing " + (M) + " x " + (M) + " board...");
System.out.println("Done.");
System.out.println();

while (!repeat) {
int X = Xvalue(M);
int Y = Yvalue(M);

int C = convertIndex(X, Y, M);

System.out.println("Marking location " + X + "," + Y + ")");
for (int i = 0; i < (Board.length); i++) {
{
Board[i] = A;
if ((i % M == 0)) {
System.out.println();
}
if (i == C) {
Board[i] = Board[i].replace(A, B);
}
if (i == C && C == -1) {
repeat = true;
}
}
System.out.print(Board[i]);
}
System.out.println();
}
}

public static int convertIndex(int x, int y, int N) {

int valX = (x - 1) * N;
int valY = y;
int targetIndex = valX + valY;

return (targetIndex - 1);

}

public static int Xvalue(int M) {
boolean repeat = false;
int X = 0;
while (!repeat) {

System.out.print("Please enter the X-coordinate: ");
String InputX = new Scanner(System.in).nextLine();
X = Integer.parseInt(InputX);
if (X > M) {
System.out.println();
System.out.println("Error, please enter a valid X Coordinate...");
repeat = false;
} else {
repeat = true;
}
}
return X;
}

public static int Yvalue(int M) {
boolean repeat = false;
int Y = 0;

while (!repeat) {
System.out.println();
System.out.print("Please enter the Y-coordinate: ");
String InputY = new Scanner(System.in).nextLine();
Y = Integer.parseInt(InputY);
if (Y > M) {
System.out.println("Error, please enter a valid Y Coordinate...");
repeat = false;
} else {
repeat = true;
}
}
return Y;
}

最佳答案

循环的问题在于它在打印数组之前定义了数组中的每个元素:

while (!repeat) {
//...
for (int i = 0; i < (Board.length); i++) {
{
Board[i] = A; //Makes each element "O"
//...
if (i == C) { //Makes only the current cooridinate "X"
Board[i] = Board[i].replace(A, B);
}
//...
}
System.out.print(Board[i]);
}
}

要修复此问题以保留旧的 X,您需要删除赋值 Board[i] = A;。但您仍然需要初始化您的板,否则您将得到空字符串。所以你需要在循环之前添加一些东西,例如:

String[] Board = new String[N];
M = (int) Math.sqrt(N);
String A = "O";
String B = "X";
//initialize board
for (int i = 0; i < Board.length; i++)
Board[i] = A;

关于java - 替换数组中的字符串并将其保留在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33962343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com