Java 如何将一维阵列与二维阵列进行比较
我想在比较两个不同维度的数组方面得到一些帮助。我想检查一维数组是否是二维数组的子数组。以下是我尝试过的:Java 如何将一维阵列与二维阵列进行比较,java,Java,我想在比较两个不同维度的数组方面得到一些帮助。我想检查一维数组是否是二维数组的子数组。以下是我尝试过的: 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) +
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");
}
}
}
}
我不知道你到底想要什么,但正如我所看到的,你需要这样的东西:
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");
}
}
}
}
我已将2D数组的第二个元素复制到另一个arrayz[],因为数组可以逐个元素进行比较,而不是直接将一个数组与另一个数组进行比较。如果您喜欢我的答案,请单击我答案上有用的标记。我需要一个简单的答案来回答可能对我来说很复杂的问题。sentinel循环是我可以在编程中用作武器库的另一个工具。非常感谢。
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");
}
}
}
}
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
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