gpt4 book ai didi

Java 将行中的每个元素与二维数组中的所有元素进行比较

转载 作者:行者123 更新时间:2023-11-30 07:56:03 25 4
gpt4 key购买 nike

我有一个二维数组,我正在尝试逐步遍历该数组,以便对于第一行,我想逐步遍历每个元素并将它们与该行中的所有其他元素进行比较以检查我的一些条件我感兴趣。然后转到下一行,执行相同的操作,然后重复,直到我遍历整个数组。我感兴趣的条件在我的 if/else block 内。

这是我的示例二维数组:

int [][] a = { {4,16,5}, {1,12,1}, {8,9,13}, {3,4,7}};

这是我的代码:

public class ArrayElementComparison {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// define the test array

int [][] a = { {4,16,5}, {1,12,1}, {8,9,13}, {3,4,7}};

for (int i = 0; i < a.length; i++) {
for (int k = 1; k < a.length; k++) {
System.out.println("a[i][k-1] " + a[i][k-1]);


if (a[i][k-1] == 4)
{
if (a[i][k] == 16)
{
System.out.println("4->16");
}
}
else if (a[i][k-1] == 12)
{
if (a[i][k] == 1)
{
System.out.println("12->1");
}
}
else if (a[i][k-1] == 9)
{
if (a[i][k] == 13)
{
System.out.println("9->13");
}
}
else if (a[i][k-1] == 3)
{
if (a[i][k] == 7)
{
System.out.println("3->7");
}
}
}

}
}

}

这是输出:

a[i][k-1] 4
4->16
a[i][k-1] 16
a[i][k-1] 5
a[i][k-1] 1
a[i][k-1] 12
12->1
a[i][k-1] 1
a[i][k-1] 8
a[i][k-1] 9
9->13
a[i][k-1] 13
a[i][k-1] 3
a[i][k-1] 4
a[i][k-1] 7

从输出中可以看出,它捕获了前 3 个条件,但没有捕获第四个条件 (3->7)。我意识到这是因为它只检查当前元素的下一个相邻元素。但是,我不知道如何修复代码,以便它检查整行,而不仅仅是下一个相邻行。

最佳答案

您需要在每个子数组中进行迭代。试试这个:

int[][] a = { { 4, 16, 5 }, { 1, 12, 1 }, { 8, 9, 13 }, { 3, 4, 7 } };

for (int i = 0; i < a.length; i++) {
int[] inner = a[i];
for (int k = 0; k < inner.length; k++) {
int current = inner[k]; // current value being compared

// copy the remaining items in the array to a new array for iterating
int[] subInner = Arrays.copyOfRange(inner, k + 1, inner.length);

for (int n = 0; n < subInner.length; n++) {
int comparedTo = subInner[n]; // current value that "current" is comparing itself to
System.out.println("array " + (i + 1) + " compare " + current + " to " + comparedTo);

if (current == 4 && comparedTo == 16) {
System.out.println("4->16");
} else if (current == 12 && comparedTo == 1) {
System.out.println("12->1");
} else if (current == 9 && comparedTo == 13) {
System.out.println("9->13");
} else if (current == 3 && comparedTo == 7) {
System.out.println("3->7");
}
}
}
}

关于Java 将行中的每个元素与二维数组中的所有元素进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32656914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com