2016-06-09 2 views
-1

이름, 성 또는 전화 번호로 연락처를 검색해야합니다. 어떻게 할 수 있습니까? 이 경우 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; 
} 
} 
+0

당신이 사용할 때마다'nextInt()는'당신은 콘솔에서 INT 읽으려고. 그래서 if 문에서 그렇게하지 마십시오. 한번 그것과'int choice = in.nextInt()'와 같은 결과를 저장하고'if (choice == 1) {..} else if (choice == 2) {..}와 같은 조건에서 그 저장된 값을 사용하십시오. '. 여기에'switch/case'를 사용할 수도 있습니다. – Pshemo

+0

결과를 저장하면 그 값을 변경할 수 없습니다.,. 나는 그 선택을 다시 만들고 싶었 기 때문에 while (true) {..}을 사용했습니다. –

+0

루프 내부에서 한 번만 읽을 수 있습니다. 그러면 각 반복에서 해당 값을 업데이트 할 수 있습니다. – Pshemo

답변

1

이이 같은 다음 자바 8에서 할 수있는 수행합니다 nome, cognomenum_Tel을 나타내는 String입니다

Optional<Contatto> result = cont.stream().filter(c -> 
    (nome == null || nome.equalsIgnoreCase(c.getNome())) 
     && (cognome == null || cognome.equalsIgnoreCase(c.getCognome())) 
     && (num_Tel == null || num_Tel.equals(c.getNum_Tel())) 
).findFirst(); 

가정하면 검색어의 기준

nome, cognomenum_Tel는 쿼리의 기준을 나타내는 Optional<String> 경우, 그 다음이 될 것입니다 :

Optional<Contatto> result = cont.stream().filter(c -> 
    nome.map(s -> s.equalsIgnoreCase(c.getNome())).orElse(true) 
     && cognome.map(s -> s.equalsIgnoreCase(c.getCognome())).orElse(true) 
     && num_Tel.map(s -> s.equals(c.getNum_Tel())).orElse(true) 
).findFirst(); 
0

가 " 삼". 방법은 전화 번호

private static Contatto SearchContattoNumber(ArrayList<Contatto> cont, int number) { 
    for (Contatto tmp : cont){ 
    if (tmp.getNum_Tel() == number) return tmp; 
    } 
    return null; 
} 

으로 검색, 예를 들어, 단순하고 매우 간단합니다 그리고 당신은 각 검색 옵션 등의 방법을 만든 다음 바로 사용자에게 물어 당신이 거 사용에있어 검색을 결정할 것 당신이 어떤 작업을 요청했던 것처럼 당신은

관련 문제