输出为
- - -
- - -
- - -
1 2 3
4 5 6
7 8 9
如果我输入1,我希望新输出为
X - -
- - -
- - -
1 2 3
4 5 6
7 8 9
我尝试过使用布尔语句和while(true),但我无法弄明白。 这是一些示例代码
String table[][];
table = new String[3][3];
int options[][]={{1,2,3},{4,5,6},{7,8,9}};
while(true){
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = "—";
System.out.print(table[i][j] + " ");
} //FOR LOOP 2
System.out.println();
}// FOR LOOP 1
for (int i = 0; i < options.length; i++) {
for (int j = 0; j < options[i].length; j++) {
System.out.print(options[i][j]+ " ");
}// FOR LOOP 2(2)
System.out.println();
}// FOR LOOP 1(1)
// ASK FOR MOVE ONE
System.out.println("Player One (x) : Enter a move from 1-9 >>> ");
int x = in.nextInt();
if (x==1){
table[0][0]="x";
return true; //DOES NOT WORK. I WANT IT TO RETURN TO TOP WITH THE VALUE table[0][0] = x
}
当我输入1时,我的输出仍然是 - - - - - - - - - 1 2 3 4 5 6 7 8 9
答案 0 :(得分:0)
使用布尔变量标志来检查条件
boolean flag=false;
if if loop assign flag true
if (x==1){
table[0][0]="x";
flag=true;
}
使用do ... while循环而不是while循环
do{
}while(flag)
以下是更新的代码:
boolean flag=false;
do{
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = "—";
System.out.print(table[i][j] + " ");
} //FOR LOOP 2
System.out.println();
}// FOR LOOP 1
for (int i = 0; i < options.length; i++) {
for (int j = 0; j < options[i].length; j++) {
System.out.print(options[i][j]+ " ");
}// FOR LOOP 2(2)
System.out.println();
}// FOR LOOP 1(1)
// ASK FOR MOVE ONE
System.out.println("Player One (x) : Enter a move from 1-9 >>> ");
int x = in.nextInt();
if (x==1){
table[0][0]="x";
flag=true;
}
}while(flag);
答案 1 :(得分:0)
您应该将数组的初始化删除到while循环之外:
// init the array
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = "—";
}
}
while(true){
// print the array
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < options.length; i++) {
for (int j = 0; j < options[i].length; j++) {
System.out.print(options[i][j]+ " ");
}// FOR LOOP 2(2)
System.out.println();
}// FOR LOOP 1(1)
// ASK FOR MOVE ONE
System.out.println("Player One (x) : Enter a move from 1-9 >>> ");
int x = in.nextInt();
if (x==1){
table[0][0]="x";
}
}
这样,您就不会在循环的每次迭代中重置数组。
另外,不要在你的条件中放置一个return语句,因为那会破坏循环并且不会打印更新的数组。
答案 2 :(得分:0)
但是,为了修复您的代码,以下操作将会如此。请仔细阅读您的解决方案以简化
int userInput = -1;
while(true){
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (userInput ==1){
table[0][0]="x";
}else {
table[i][j] = "—";
}
System.out.print(table[i][j] + " ");
} //FOR LOOP 2
System.out.println();
}// FOR LOOP 1
for (int i = 0; i < options.length; i++) {
for (int j = 0; j < options[i].length; j++) {
System.out.print(options[i][j]+ " ");
}// FOR LOOP 2(2)
System.out.println();
}// FOR LOOP 1(1)
// ASK FOR MOVE ONE
System.out.println("Player One (x) : Enter a move from 1-9 >>> ");
userInput = in.nextInt();