2016-04-27 79 views
-6

所以,我有ArrayList中,我儲存的動物。將ArrayList <String>打印成輸出?

private ArrayList<Animal> catalog = new ArrayList<>(); 

現在,我需要打印目錄到我的輸出當我按下4到我的輸出。

case 4: 
       System.out.println("List of animals: "); 
       printIt(); //Function to print catalog 
       break; 

我試着用

private boolean InList(String name) { 
    for (int i = 0; i < catalog.size(); i++) { 
     if (name.equalsIgnoreCase(catalog.get(i).getName())) { 
      return true; 
     } 
    } 
    return false; 
} 

做,但它不工作。你們能幫我拿到這段代碼嗎?

+0

更多信息,你爲什麼不只是嘗試打印動物名錄? –

+1

請將'printIt',以及'InList'如何相關? –

+1

當我嘗試只打印「目錄」中存儲的動物,我會得到「[[email protected]]」 爲printit在這裏 私人字符串爲printit(){ 字符串動物=名稱; //catalog.add(); 歸還動物; } –

回答

0

如果你想讓它返回一個字符串,可以這樣做。

String printIt(ArrayList<Animal> animals) { 
String temp = ""; 
for(Animal animal : animals) { 
temp += animal.getName() + "\n"; 
} 
return temp; 
} 

儘管我沒有看到有此需要,但只需立即打印即可。

void printIt(ArrayList<Animal> animals) { 
for(Animal animal : animals) { 
System.out.println(animal.getName()); 
} 
} 
+0

謝謝。使用第二個選項。你是對的,更好的一個:p –

0

定義,打印也許是太多的方法,你可以做

System.out.println("List of animals: "+ catalog); 

但你必須覆蓋類動物的toString方法...

,如果你不要重複,你會得到東西打印像

[[email protected]] 

這是d efaukt對象的字符串...

類似的格式爲:

[email protected] ..

+0

謝謝。不完全確定「如何重寫」toString,但它現在起作用。 –