问题描述
我想比较两个行均在不同的顺序,从一个二维数组,并存储元素从两行相同。下面是我所生产的一个例子:
I am trying to compare two rows that are in different order from a 2D array, and store elements that are the same from both rows. Here's an example of what I have produced:
String[] row1 = new String[10];
String[] row2 = new String[10];
String[][] fruit = {{"apple", "banana", "kiwi"},{"kiwi", "oranges", "grapes"}};
for (int i = 0; i < fruit.length; i++ ) {
for (int j = 0; j < fruit[i].length; j++){
if(fruit[0][j].equals(fruit[1][j])) {
row1[j] = fruit[0][j];
row2[j] = fruit[1][j];
System.out.println("Match found");
}else{
System.out.println("Not found");
}
}
}
System.out.println("row1");
System.out.println(Arrays.deepToString(row1));
System.out.println("row2");
System.out.println(Arrays.deepToString(row2));
我想要的ROW1 []和ROW2 []来存储是相同的(这是猕猴桃在本实施例)中的元素。然而,问题是.equals功能只能检测匹配模式。上面只有例如,从ROW1和ROW2打印出空值。
I want the row1[] and row2[] to store the elements that are the same (which is kiwi in this example). However, the problem is .equals function only detects matching patterns. The example above only prints out nulls from row1 and row2.
它应该打印出来:
row1
[kiwi]
row2
[kiwi]
请注意:我不想申报... 字符串检查=猕猴桃;
,因为用户可以输入二维数组中的任何东西。
Note: I don't want to declare... String check = "kiwi";
because the user can enter anything in the 2D array.
有什么建议?我觉得我越来越接近。我看到有人用.equals的一个类似的例子和工作,但它只是单一的阵列。
Any suggestions? I feel I am getting close. I saw a similar example of someone using .equals and that worked, but it was only for single arrays.
推荐答案
您for循环的限制已经搞砸了,以及你比较访问数组元素。我猜你想这样的事情...
The limits of your for-loops have been messed up, as well as the array elements that you accessed for comparison. I guess you wanted something like this...
import java.util.Arrays;
public class RowCompare
{
public static void main(String[] args)
{
String[] row1 = new String[10];
String[] row2 = new String[10];
String[][] fruit = {{"apple", "banana", "kiwi"},{"kiwi", "oranges", "grapes"}};
for (int i = 0; i < fruit[0].length; i++ ) {
for (int j = 0; j < fruit[1].length; j++){
if(fruit[0][i].equals(fruit[1][j])) {
row1[i] = fruit[0][i];
row2[j] = fruit[1][j];
System.out.println("Match found");
}else{
System.out.println("Not found");
}
}
}
System.out.println("row1");
System.out.println(Arrays.deepToString(row1));
System.out.println("row2");
System.out.println(Arrays.deepToString(row2));
}
}
但你应该描述你想要的结果做什么。这些固定大小的结果数组(字符串[10])看上去半信半疑,以及当前草图code不能容易地推广超过2行。有可能是使用一个更优雅的解决方案设置
和列表
取值....
这篇关于两排在一个单一的二维数组比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!