在比较两个不同维度的数组时,我需要一些帮助。我想检查一维数组是否是二维数组的子数组。这是我尝试过的:
public static void compare() {
int[][] x = {{23, 33, 46, 50, 56},
{3, 8, 65, 34, 90},
{2, 7, 46, 50, 56}};
int[] y = {2, 7, 46, 50, 56};
for (int i = 0; i < x.length - (x.length) + 1; i++) {
System.out.println(Arrays.toString(x[2]));
for (int j = 0; j < y.length - (y.length) + 1; j++) {
System.out.println(Arrays.toString(y));
if (x[2].equals(y)) {
System.out.println("match");
} else {
System.out.println("no match");
}
}
}
}
答案 0 :(得分:1)
我不知道您到底想要什么,但据我所知-您需要类似的东西:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[][] x = {{23, 33, 46, 50, 56},
{3, 8, 65, 34, 90},
{2, 7, 46, 50, 56}};
int[] y = {2, 7, 46, 50, 56};
for (int[] aX : x) {
System.out.println(Arrays.toString(x[2]));
if (Arrays.equals(aX, y)) {
System.out.println("match");
} else {
System.out.println("no match");
}
}
}
}
答案 1 :(得分:0)
int[][] x = {{23, 33, 46, 50, 56},
{3, 8, 65, 34, 90},
{2, 7, 46, 50, 56}};
int[] y = {2, 7, 46, 50, 56};
for (int[] i : x) {
if (Arrays.equals(y, i)) {
System.out.println("match");
}
}
答案 2 :(得分:0)
import java.util.*;
public class ArrayMatch {
public static void main(String[] args){
int[][] x = {{23, 33, 46, 50, 56},
{3, 8, 65, 34, 90},
{2, 7, 46, 50, 56}};
int[] y = {2, 7, 46, 50, 56};
String yArray = Arrays.toString(y);
boolean match = false;
for(int i = 0; i < x.length; i++) {
String comparison = Arrays.toString(x[i]);
if(comparison.equals(yArray)) {
match = true;
}
}
if(match) {
System.out.println("Match");
}
else
System.out.println("No match");
}
}
这是您的输出:
Match
答案 3 :(得分:0)
int[][] x = { { 23, 33, 46, 50, 56 }, { 3, 8, 65, 34, 90 }, { 2, 7, 46, 50, 56 } };
int[] y = { 2, 7, 46, 50, 56 };
int[] z = x[2].clone();
int count = 0;
for (int i = 0; i < z.length; i++) {
if (z[i] != y[i]) {
System.out.println("Not Match");
break;
} else {
count++;
if (count == y.length) {
System.out.println("Match");
break;
} else {
continue;
}
}
}
输出为:
Match
我已将2D数组的第二个元素复制到另一个数组(z []),因为可以将一个数组与一个元素进行比较,而不是将一个数组直接与另一个数组进行比较。如果您喜欢我的回答,请单击我的答案。