[英]Java-How to print specific array from a list?
我创建了一个arraylist,在用扫描仪输入名称后,我想搜索名称是否等于getName,然后使用voce.get(i).toString()打印整个数组。
像搜索robert一样,它搜索所有arraylist,并在找到一个与robert打印al array相等的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;
}
}
主要:
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());
}
}
}
}
如果我正确理解,我认为您正在尝试查看是否在数组列表“ voce”中找到了来自Scanner的输入。
您需要遍历“ voce”,直到看到“ chiave”。
for(Item item: voce) {
if(item.getNome().equals(chiave) {
System.out.println("Found: " + item.getNome());
}
}
您想将每个Item
的nome
属性与输入字符串进行比较-尝试在您提到的行上使用voce.get(i).getNome()
。
您需要从Item对象调用getNome()方法,如下所示:
for(int i = 0; i < voce.size(); i++){
String nome = voce.get(i).getNome();
if(chiave.equals(nome){
System.out.println(nome);
}
}
您正在尝试使用item类中的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());
}
}
希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.