2016-06-23 36 views
0

我创建了一个arraylist,在我用扫描器输入名称后,我想搜索名称是否等于getName,然后用voce.get(i).toString()打印整个数组。Java - 如何从列表中打印特定数组?

与搜索robert一样,它搜索所有arraylist,并且找到一个getName与robert print al数组相同的getName。

对不起我的英文不好

public class Item { 
private String nome,indirizzo,cellulare; 

public Item(String nome, String indirizzo, String cellulare){ 
    this.nome = nome; 
    this.indirizzo = indirizzo; 
    this.cellulare = cellulare; 
} 

public String toString(){ 
    return this.getNome() + this.getIndirizzo() + this.getCellulare(); 
} 

public String getNome() { 
    if(!this.nome.isEmpty()){ 
     return this.nome; 
    } 
    else{ 
     return "Sconosciuto"; 
    } 
} 

public void setNome(String nome) { 
    this.nome = nome; 
} 

public String getIndirizzo() { 
    if(!this.indirizzo.isEmpty()){ 
     return this.indirizzo; 
    } 
    else { 
     return "Sconosciuto"; 
    } 
} 

public void setIndirizzo(String indirizzo) { 
    this.indirizzo = indirizzo; 
} 

public String getCellulare() { 
    if(!this.cellulare.isEmpty()){ 
     return this.cellulare; 
    } 
    else { 
     return "Sconosciuto"; 
    } 
} 

public void setCellulare(String cellulare) { 
    this.cellulare = cellulare; 
} 
    } 

MAIN:

import java.util.*; 



public class AggPersone { 
public static void main(String[] args) { 


    ArrayList<Item> voce = new ArrayList<Item>(); 

    voce.add(new Item("Robert", "Via qualcosa", "123")); 
    voce.add(new Item("Roberto","Via qualcosina", "123")); 

    Scanner input = new Scanner(System.in); 
    System.out.println("chi cerchi?"); 
    String chiave = input.nextLine(); 


    for(int i = 0; i < voce.size(); i++){ 
     if(chiave.equals(getNome){ <---- doesn't work, how to ispect getNome? 
      System.out.println(voce.get(i).toString()); 
     } 
    } 

} 
    } 

回答

0

要将每个Item的比较nome属性输入字符串 - 试试在你提到的线路使用voce.get(i).getNome()

+0

非常感谢你,如果这个名字不存在,我怎么能打印出“没有发现的人?”。我假设我不知道arraylist的确切数量。 – Uruma

+0

@ Uruma-在你试图找到名字的'if'之后加上else语句。 – vv88

+0

是的,但如果这个名字在3-4的地方,它会被打印2次,直到找到它。它应该在迭代结束时打印出来。 – Uruma

0

您需要从项目对象调用getNome()方法,像这样:

for(int i = 0; i < voce.size(); i++){ 
    String nome = voce.get(i).getNome(); 
    if(chiave.equals(nome){ 
    System.out.println(nome); 
    } 
} 
1

如果我理解正确的话,我觉得你是想看看是否从扫描仪输入的发现数组列表'voce'。

您需要迭代'voce',直到看到'chiave'。

for(Item item: voce) { 
    if(item.getNome().equals(chiave) { 
     System.out.println("Found: " + item.getNome());   
    } 
} 
0

您正在尝试使用 - 从项目类getNome()方法未做这个类的一个对象。因此它甚至没有编译。

您的最后一个循环更改为以下 -

for(int i = 0; i < voce.size(); i++){ 
       if(chiave.equals(voce.get(i).getNome())){ //<---- doesn't work, how to ispect getNome? 
        System.out.println(voce.get(i).toString()); 
       } 
      } 

希望有所帮助。