此對象是一包口香糖。每種口香糖都是獨一無二的。我們建立了一個可容納12顆牙齦的包。我們用新的口香糖填充包裝。我們必須檢查包裝,看看這種口香糖是否已經裝入包裝中。包裝中的每個口香糖必須是獨特的。Java嵌套循環防止重複
public PackOfGum()
{
pack = new Gum[12];
// Successfully populate pack with gum
for (int i=0; i<12; i++) {
pack[i] = new Gum();
// Failure preventing duplicate gums. Idea is to look in the pack
// at all of the gums that came before this one, and see if this one
// matches any of them. While yes and it is a duplicate, then choose
// a new gum.
for (j=0; j<i; j++) {
while (pack[i] == pack[j]) {
pack[i] = new Gum();
}
}
}
}
我未能正確地檢查所有以前的牙齦,並將它們與當前口香糖比較。這應該如何正確完成?
我不知道我是否正確理解您的問題。但是如果你只是想存儲一個非重複的槍支集合,那麼你可以使用java.util.Set來存儲它。您需要在Gum類中實現equals方法來定義相等條件。 –
一個問題:你如何比較膠質物體?使用其內存地址或其值? – MaxZoom
口香糖「種類」的定義是什麼?您現在正在比較兩個Gum引用是否指向相同的Gum對象實例。鑑於你正在爲數組中的每個元素創建一個新的Gum實例,它總是會有所不同。 –