Java 比较int数组元素值
正在尝试比较数组的元素。例如,如果数组[0][0]等于数组[0][1],则希望返回布尔值。我想,如果两个元素不相等,那就更容易了。所以Java 比较int数组元素值,java,arrays,int,compare,Java,Arrays,Int,Compare,正在尝试比较数组的元素。例如,如果数组[0][0]等于数组[0][1],则希望返回布尔值。我想,如果两个元素不相等,那就更容易了。所以 boolean rowAlike = true; for(int row = 0; row<size; row++) { for(int col = 0;col<size;col++) { nextNum = col + 1; if(
boolean rowAlike = true;
for(int row = 0; row<size; row++)
{
for(int col = 0;col<size;col++)
{
nextNum = col + 1;
if(!square[row][col].equals(square[row][nextNum]))
rowAlike=false;
}
if(rowAlike)
System.out.println("All digits are the same in row " +row++);
我要么得到一个false,要么得到一个编译器错误
编辑:当使用==
时,我收到的false错误是使用.equals
ExploreMatrix.java:89:error:int无法取消引用
当使用array.equals时
java:89:错误:找不到适用于equals(int,int)的方法
原语(如int
)由=
和/或的值进行测试=代码>(视情况而定)。您需要在循环体中定义行相似性
(否则它不会在下一行重置)。当col==size-1
时访问col+1
将产生一个ArrayIndexOutOfBounds。我建议您从1开始
,然后与上一个进行比较。接下来,当您第一次发现不匹配的值时,可以在循环中中断。最后,对于显示,不应修改行的值
(否则将跳过一行)。总而言之
int[][] square = new int[size][size];
//
// ... Setup values in square ...
//
for (int row = 0; row < size; row++) {
boolean rowAlike = true;
for (int col = 1; col < size; col++) {
if (square[row][col - 1] != square[row][col]) {
rowAlike = false;
break;
}
}
if (rowAlike) {
System.out.printf("All digits are the same in row %d%n",
row + 1);
}
}
int[][]square=新的int[size][size];
//
// ... 以正方形设置值。。。
//
对于(int row=0;row
如果您的方块
是字符串的数组
,则上述代码将起作用
不幸的是,您没有在问题中定义square
使用=
比较基本类型,如int
和。使用equals
比较字符串
代码中存在多个问题:
- 最有可能发生
ArrayIndexOutOfBoundsException
(这是一个
RuntimeException
)此处:
用于(int col=0;col我要么得到一个false,要么得到一个编译器错误。
好吧,是哪一个?如果是编译器错误,为什么不在你的问题中分享它呢?抱歉,无意中遗漏了代码的这一部分。square是二维数组。大小由用户设置。两个维度总是相同的。你可以编辑你的问题。和格式它。所以数组是一种引用类型。但是int
是一种基本类型。关于错误,你不了解什么?我了解错误。我想知道,如果有办法,我如何比较这两个元素。.equals
对任何对象(即非基本类型)都有效(编译),因为equals
-方法是在java.lang.Object
中定义的。
int[][] square = new int[size][size];
//
// ... Setup values in square ...
//
for (int row = 0; row < size; row++) {
boolean rowAlike = true;
for (int col = 1; col < size; col++) {
if (square[row][col - 1] != square[row][col]) {
rowAlike = false;
break;
}
}
if (rowAlike) {
System.out.printf("All digits are the same in row %d%n",
row + 1);
}
}
if(!square[row][col].equals(square[row][nextNum]))
for(int col = 0;col<size;col++){
nextNum = col + 1;
if(!square[row][col].equals(square[row][nextNum]))
//...
}