当2d阵列没有任何" X"时,我想让我的程序退出。留在里面。我用" 1"替换它们。用户输入(x和y)。我该怎么办?而且,如果您在我的代码中发现错误,如果您能指出这一点,我将非常感激。
import java.util.Scanner;
public class MultiArrays {
public static void main(String[] args) {
MultiArrays mu = new MultiArrays();
String firstArray[][] = { { "X", "X", "X" }, { "X", "X", "X" } };
boolean quit = true;
do {
mu.display(firstArray);
mu.pickNum(firstArray);
mu.display(firstArray);
System.out.println();
} while (quit == true);
}
public void display(String x[][]) {
for (int row = 0; row < x.length; row++) {
for (int col = 0; col < x[row].length; col++) {
System.out.print(x[row][col] + "\t");
}
System.out.println();
}
}
public void pickNum(String x[][]) {
System.out.println("Pick row number (0-1) >");
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
System.out.println("Pick column number (0-2) >");
int num2 = scan.nextInt();
x[num][num2] = "1";
}
}
答案 0 :(得分:-1)
将quit
变量设置为true
,您可以执行以下操作:
boolean quit=true;
do { // no matter what value quit has, we would loop at least once
mu.display(firstArray);
mu.pickNum(firstArray);
mu.display(firstArray);
System.out.println();
for (int row = 0; row < firstArray.length; row++) {
for (int col = 0; col < firstArray[row].length; col++) {
quit &= !firstArray[row][col].equalsIgnoreCase("X"); // do boolean AND while checking each element if it is something else than "X"
}
}
} while (!quit); // stop looping when quit is set to true
该行
quit &= !firstArray[row][col].equalsIgnoreCase("X");
quit = quit & !firstArray[row][col].equalsIgnoreCase("X") // the same but longer
当且仅当所有元素 true
时,评估为"X"