比较2D数组中行或列的元素(Java) [英] Compare elements of rows or columns in 2D array (Java)
本文介绍了比较2D数组中行或列的元素(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 String [] []字段
.例如,它可能看起来像:
I have a String[][] field
. For example, it may look like:
[xy] [xy] [xy] [xy] [xy]
[xy] [xy] [xy] [xy] [xy]
[xy] [xy] [xy] [xy] [xy]
[xy] [xy] [xy] [xy] [xy]
[xy] [xy] [xy] [xy] [xy]
行和列的数量相等,但是每次的数量可能不同.我需要检查整个行或整个列的元素值是否相等.我为3x3 field
编写了一些错误的代码来检查行,这里是:
Number of rows and columns is equal, but number may be different each time. I need to check if the values of elements of entire row or entire column are equal.
I have written some bad code for 3x3 field
to check line, here it is:
public boolean checkHorizontal(String[][] field) {
boolean value = false;
int x = 0;
for (int i = 0; i < field.length; i++) {
if (field[i][x].equals(field[i][x + 1]) &&
field[i][x + 1].equals(field[i][x + 2]) &&
!field[i][x].equals("[something]")) {
value = true;
}
}
return value;
}
但这不是通用的检查行的方法,因为我们可能具有大小不同的矩阵(并且需要添加 x + 3
, x + 4
, x + 5
等)有没有有效的方法来比较2D数组的整个行/列?
But it's not universal way to check line, because we may have a matrix of different size (and need to add x + 3
, x + 4
, x + 5
, etc.)
Is there any effective way to compare entire row/column of 2D array?
推荐答案
要检查所有行:
for(int i = 0; i < field.length; i++){
for(int j = 1; j < field[i].length; j++){
if(!field[i][0].equals(field[i][j])){
return false;
}
}
}
return true;
这篇关于比较2D数组中行或列的元素(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文