package quiz;
public class PhoneMain {
/***
*
과제)
이름(name), 전화번호(tel) 필드와 생성자 등을 가진 Phone 클래스를 작성하고
실행 예시와 같이 작동하도록 구현해 주세요
실행)
1.입력|2.검색|3.프로그램종료
메뉴를 선택해 주세요 >> 1
인원수 >> 3
이름과 전화번호 >> 황기태 777-7777
이름과 전화번호 >> 감자바 111-1111
이름과 전화번호 >> 김기태 222-2222
메뉴를 선택해 주세요 >> 2
검색할 이름 >> 김기명
김기명이 없습니다
메뉴를 선택해 주세요 >> 2
검색할 이름 >> 감자바
감자바의 번호는 111-1111 입니다
메뉴를 선택해 주세요 >> 3
프로그램 종료..
이메일) jhyoun72002@naver.com => 여기로 보내주시면 감사하겠습니다 ~~ ^^
*/
}
정답코드)
package quiz;
import java.util.Scanner;
class Phone {
private String name; // 이름
private String tel; // 전화번호
public Phone(String name, String tel) {
this.name = name;
this.tel = tel;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
public class PhoneMain {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Phone[] phone = null;
while(true) {
System.out.println("1.입력|2.검색|3.프로그램종료");
System.out.println("메뉴를 선택해 주세요 >> ");
int choice = sc.nextInt();
if(choice == 1) {
System.out.println("인원수 >> ");
int count = sc.nextInt();
phone = new Phone[count]; // 인원수만큼 객체배열 할당
// 루프 돌면서 이름과 전화번호를 입력받아 phone 객체를 배열에 저장
for(int i = 0; i < phone.length; i++) {
System.out.println("이름과 전화번호(이름과 번호 입력) >> ");
String name = sc.next();
String phoneNumber = sc.next();
phone[i] = new Phone(name, phoneNumber);
}
} else if(choice == 2) {
System.out.println("검색할 이름 >> ");
String search_name = sc.next();
boolean flag = false;
for(int i = 0; i < phone.length; i++) {
if(phone[i].getName().equals(search_name)) {
System.out.println(search_name + "의 번호는 "
+ phone[i].getTel() + "입니다.");
flag = true;
}
}
if(!flag) {
System.out.println(search_name + " 이름은 없습니다.");
}
} else if(choice == 3) {
System.out.println("프로그램 종료");
break;
}
}
}
}