我创建了一个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());
}
}
}
}
非常感谢你,如果这个名字不存在,我怎么能打印出“没有发现的人?”。我假设我不知道arraylist的确切数量。 – Uruma
@ Uruma-在你试图找到名字的'if'之后加上else语句。 – vv88
是的,但如果这个名字在3-4的地方,它会被打印2次,直到找到它。它应该在迭代结束时打印出来。 – Uruma