Main
package quiz;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 변수 선언
Handler handler = new Handler(); // main과 상호작용할 handler 객체
PhoneBook tmp = null;
String name = null, pnum = null;
Scanner sc = new Scanner(System.in);
ArrayList<PhoneBook> list = null;
int menu, index;
// 연산 및 처리
while(true) {
System.out.println("1. 추가");
System.out.println("2. 목록");
System.out.println("3. 삭제");
System.out.println("4. 정렬");
System.out.println("0. 종료");
System.out.print("선택 >>> ");
menu = Integer.parseInt(sc.nextLine());
switch(menu) {
case 1:
System.out.print("이름 입력 : ");
name = sc.nextLine();
System.out.print("전화번호 입력 : ");
pnum = sc.nextLine();
// main에서 index를 지정하지 않아도, handler에서 다시 배정해준다
tmp = new PhoneBook(0, name, pnum);
handler.insert(tmp);
break;
case 2:
list = handler.select();
list.forEach(ob -> System.out.println(ob));
break;
case 3:
System.out.print("삭제할 정보의 번호를 입력 : ");
index = Integer.parseInt(sc.nextLine());
handler.delete(index);
break;
case 4:
handler.sort();
break;
case 0:
handler.save();
sc.close();
return;
}
System.out.println();
}
}
}
PhoneBook
package quiz;
import java.io.Serializable;
public class PhoneBook implements Serializable, Comparable<PhoneBook> { // 직렬화 가능하도록
// 이름과 전화번호를 멤버필드
// 필드를 전달받는 생성자
// getter/setter
// toString()
private static final long serialVersionUID = 1234L;
private int index;
private String name;
private String pnum;
public PhoneBook(int index, String name, String pnum) {
this.index = index;
this.name = name;
this.pnum = pnum;
}
@Override
public int compareTo(PhoneBook o) {
String othersName = o.getName(); // 대상의 이름을 변수에 담고
int diff = name.compareTo(othersName); // 내 이름과 대상의 이름 비교값의 결과(차이)
return diff; // 차이값을 정수로 반환한다 (0보다 큰지 같은자 작은지)
}
@Override
public String toString() {
return String.format("%d) %s : %s", index, name, pnum);
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
}
Handler
package quiz;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Handler {
private ArrayList<PhoneBook> list = new ArrayList<>();
private File f;
private static int sequence = 1000;
public Handler() { // Handler의 객체를 생성하면
f = new File("phonebook.dat"); // 파일을 지정하고
if(f.exists()) { // 만약 파일이 이미 만들어져 있다면 (저장된 내용이 있다면)
list = load(); // 파일을 불러와서 리스트에 올려둔다
// sequence = list.stream().mapToInt(x -> x.getIndex()).max().getAsInt();
for(PhoneBook p : list) {
if(sequence < p.getIndex()) {
sequence = p.getIndex();
}
}
}
}
@SuppressWarnings("unchecked") // 경고를 억제한다 (타입이 확인되지 않은 다운캐스팅에 대한 경고)
private ArrayList<PhoneBook> load() {
ArrayList<PhoneBook> tmp = new ArrayList<PhoneBook>();
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(f));
tmp = (ArrayList<PhoneBook>) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try { ois.close(); } catch(Exception e) {}
}
return tmp;
}
public void save() {
// 멤버 필드 list 를 f 파일에 저장하는 내용
// main에서 프로그램 종료를 실행하면, 저장 후 종료하도록 설정해야 한다
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(f); // FileNotFoundException
oos = new ObjectOutputStream(fos); // IOException
oos.writeObject(list); // IOException
oos.close();
} catch(FileNotFoundException e) { // 가장 먼저 처리하고 싶은 예외
System.out.println("파일이 존재하지 않습니다");
} catch(IOException e) {
System.out.println("입출력 진행 중 예외가 발생했습니다");
} catch(Exception e) {
System.out.println("기타 알수 없는 예외가 발생했습니다");
}
}
public void insert(PhoneBook ob) {
ob.setIndex(++sequence);
list.add(ob);
}
public void delete(int index /*매개변수 타입 자유 (권장값은 int index)*/) {
list.removeIf(ob -> ob.getIndex() == index);
}
public ArrayList<PhoneBook> select() {
return list;
}
public void sort() {
// 리스트를 이름으로 정렬하는 코드
list.sort(null);
}
}
'AWS CLOUD FRAMEWORK > Java' 카테고리의 다른 글
[Day18] Ex01 (0) | 2023.04.07 |
---|---|
[Day18] Ex01_Server (0) | 2023.04.07 |
[Day17] Ex08 (0) | 2023.04.06 |
[Day17] Ex07 (0) | 2023.04.06 |
[Day17] Ex06 (0) | 2023.04.06 |