我想檢查每行第一個元素(左側)中的所有匹配元素,如果匹配,請獲取它旁邊的元素。比較2D數組中每一行的第一個元素
這裏是我有作爲一個例子:
ArrayList<String> variables = new ArrayList<String>();
ArrayList<String> attribute = new ArrayList<String>();
String[][] sample = { {"hates", "hates"},
{"p1","boy"},
{"p2","girl"},
{"hatesCopy", "hatesCopy"},
{"p2","boy"},
{"p1","girl"}};
for(int a = 0; a < sample.length; a++){
for(int b = 0; b < sample.length; b++){
if(sample[b].equals(sample[a])){
variables.add(sample[b][0]);
attribute.add(sample[b][1]);
}
}
}
System.out.println("variables stored: "+ variables);
System.out.println("attributes stored: "+ attribute);
我試圖比較二維數組中的每一行的第一個元素,以檢查是否存在一個匹配的元素,但它不工作我想要的方式。
的變量和屬性陣列應該輸出:
variables stored: [p1, p1, p2, p2]
attribute stored: [boy, girl, girl, boy]
當第一元件「P1」是下一個從樣品2D陣列它「男孩」的值。
但是,相反,我的代碼,就決定輸出二維數組這是不對的整個事情:
variables stored: [hates, p1, p2, hatesCopy, p2, p1]
attribute stored: [hates, boy, girl, hatesCopy, boy, girl]
此外,該行的長度發生變化,但列將永遠是2的大小。 關於我要去哪裏的任何想法都是錯誤的?
'sample'是一個2D數組,但您正在檢查'sample [b] .equals(sample [a])''。這比較了1D數組,而不是String元素。你需要兩個索引來獲取一個元素(例如'sample [b] [c]')。 – collinjsimpson
是的,我試過使用樣本[b] [0] .equals(樣本[a] [0]),只輸出:變量存儲:[hates,p1,p1,p2,p2,hatesCopy,p2,p2,p1,p1 ] 屬性存儲:[恨,男孩,女孩,女孩,男孩,恨,複製,女孩,男孩,男孩,女孩] – user3273108