Len*_*all 2 java arrays boolean
我试图检查我的2D阵列是否对称.我写了一个方法来检查数组是否对称.它总是返回true,即使我更改了输入数组中的元素.我究竟做错了什么?
这是我的代码:
public class learnigBoolean
{
public static void main(String[] args)
{
int[][] array = {
{ 1, 1, 4, -1},
{ 1, 5, 0, -1},
{ 4, 0, 1, -4},
{-1, -1, 4, 10}
};
System.out.println(symetrisk(array));
}
public static boolean symetrisk(int[][] f)
{
for (int out = 0; out < f.length; out++) {
for (int in = 0; in < f[out].length; in++) {
if (f.length == f[out].length && f[out][in] == f[out][in]) {
return true;
}
}
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
if(f.length==f[out].length && f[out][in]==f[out][in])
Run Code Online (Sandbox Code Playgroud)
第一次检查确保你的矩阵是平方的,第二次检查什么都不做!您正在将每个元素与自身进行比较.
你的意思是:
if(f.length==f[out].length && f[out][in]==f[in][out])
Run Code Online (Sandbox Code Playgroud)
但正如Michael Faisst所说,你的退货声明是有问题的.
你需要这样的东西:
for (int out = 0; out < f.length; out++) {
for (int in = 0; in < f[out].length; in++) {
if (f.length != f[out].length || f[out][in] != f[in][out])) {
return false;
}
}
}
return true;
Run Code Online (Sandbox Code Playgroud)
通过反转检查,确保在返回true之前检查每个元素.
可以这样想:你只需要找到一个不满足条件的元素来表示你的数组不对称.但是,您需要检查每个元素,然后才能说出阵列是对称的.
你正在做相反的事情,说只有一次检查后数组是对称的.