2016-04-27 82 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,但它现在起作用。 –