我需要复制一个2D布尔数组并将每个布尔值更改为相反的...将true更改为false,将false更改为true。我意识到我的代码中也存在其他一些问题,但这是我的主要问题。
我收到以下错误:
错误:不兼容的类型:boolean []无法转换为boolean [] []
boolean [] [] newArray = new boolean [array.length];
错误:找不到符号
if(newArray [i] [i] = false)
if语句中的每个[i]变量都有相同的错误。
public class mod4Lec
{
public static void main(String[] args) {
//Creates array of boolean
boolean[][] array = {
{true, false, true, false},
{false, true, false, true},
{true, false, true, false},
{false, true, false, true},
};
System.out.println("Before: ");
//Prints original array
for(int row=0; row<array.length; row++) {
for(int column=0; column<array[row].length; column++)
System.out.print(array[row][column] + " ");
System.out.println();
}
}
//Pass array to method
public static void swapArray(boolean[][] array){
//Copy array
boolean[][] newArray = new boolean[array.length];
for (int column = 0; column < array.length; column++)
newArray[row][column] = array[row][column];
//Search for boolean true and switch to false
for (int i = 1; i < newArray.length; i++){
if(newArray[i][i] = true)
newArray[i][i] = false;
}
//Search for boolean false and switch to true
if(newArray[i][i] = false){
newArray[i][i] = true;
}
return newArray;
}
}
答案 0 :(得分:2)
只需迭代数组并转到
array[row][column] = ! array[row][column];
甚至更短:
array[row][column] ^= true;
(使用XOR运算符“否定”矩阵中每个单元格的当前内容)
这就是切换布尔值所需的一切!绝对不需要创建另一个数组。那里的所有代码都可能消失!
所以真正的答案:学习布尔类型的所有基础知识......在研究数组之前。含义:了解运营商之类的!不是这样你可以正确使用它们。
答案 1 :(得分:-1)
我对你的代码进行了一些评论(并修改),研究它。
public class Mod4Lec { //class names are started from Uppercase letter
public static void main(String[] args) {
// Creates array of boolean
boolean[][] array = { { true, false, true, false }, { false, true, false, true }, { true, false, true, false },
{ false, true, false, true }, };
System.out.println("Before: ");
// Prints original array
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++)
System.out.print(array[row][column] + " ");
System.out.println();
}
boolean[][] newArray = swapArray(array);
System.out.println("After: ");
for (int row = 0; row < newArray.length; row++) {
for (int column = 0; column < newArray[row].length; column++)
System.out.print(newArray[row][column] + " ");
System.out.println();
}
}
// Pass array to method
public static boolean[][] swapArray(boolean[][] array) { //return 2d array, not void
// Copy array
// you should have 2d array here, my guess is that every array "row" is of the same size
boolean[][] newArray = new boolean[array.length][array[0].length];
// again, we have 2d array and need to go for each rows to each columns
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++)
newArray[row][column] = array[row][column];
}
// Search for boolean true and switch to false
// the same 2d
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray[i].length; j++) //2nd dimension
newArray[i][j] = !newArray[i][j]; // just invert
}
return newArray;
}
}