이름, 성 또는 전화 번호로 연락처를 검색해야합니다. 어떻게 할 수 있습니까? 이 경우 java 8 스트림을 사용할 수 없다고 생각합니다 ... 또 다른 사항 ... 모든 연락처 목록을 보려면 두 번 "2"를 눌러야하지만 구현이 나에게 맞는 것처럼 보입니다. ArrayList에서 검색하는 방법은 무엇입니까?
코드 :import java.util.ArrayList;
import java.util.Scanner;
public class Test1 {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<Contatto> cont = new ArrayList<Contatto>();
int a;
try{
while (true){
System.out.println("Per inserire nuovo contatto premere 1");
System.out.println("Per visionare l'elenco dei contatti premere 2");
System.out.println("Per cercare un contatto premere 3");
a= in.nextInt();
//if you press1 you add new contact
if (a == 1){
cont.add(new Contatto());
}
//if you press2 you'll see all the contact list.
else if (a == 2){
for (Contatto tmp : cont){
String tm = tmp.dammiDettagli(tmp);
System.out.println(tm);
}
}
//if you press 3 you'll be able to search a contact by name or
//surname or telephone number
else if (a == 3){
System.out.println("Cerca contatto:");
}
else {
System.out.println("Inserimento dati errato");
}
}
}finally {
in.close();
}
}
}
이는 공용 클래스 Contatto입니다 : 당신의 선택에 그 방법을 수행중인 검색의 각 유형에 대한 방법을 추가하고 호출 할 수 있습니다
import java.util.Scanner;
public class Contatto {
private String nome;
private String cognome;
private String num_Tel;
Contatto(){
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Creazione nuovo contatto...");
System.out.println("Inserire il nome:");
//set name
setNome(in.next());
System.out.println("Inserire il cognome:");
//set surname
setCognome(in.next());
System.out.println("Inserire il numero di telefono:");
//set telephone number
setNum_Tel(in.next());
}
//method to search contact
public String cercaContatto(String in){
}
public String dammiDettagli(Contatto contatto){
return getNome() +" "+ getCognome() +" "+ getNum_Tel();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getNum_Tel() {
return num_Tel;
}
public void setNum_Tel(String num_Tel) {
this.num_Tel = num_Tel;
}
}
당신이 사용할 때마다'nextInt()는'당신은 콘솔에서 INT 읽으려고. 그래서 if 문에서 그렇게하지 마십시오. 한번 그것과'int choice = in.nextInt()'와 같은 결과를 저장하고'if (choice == 1) {..} else if (choice == 2) {..}와 같은 조건에서 그 저장된 값을 사용하십시오. '. 여기에'switch/case'를 사용할 수도 있습니다. – Pshemo
결과를 저장하면 그 값을 변경할 수 없습니다.,. 나는 그 선택을 다시 만들고 싶었 기 때문에 while (true) {..}을 사용했습니다. –
루프 내부에서 한 번만 읽을 수 있습니다. 그러면 각 반복에서 해당 값을 업데이트 할 수 있습니다. – Pshemo