Viewer part
HashMap과 TreeMap을 이용한 console 프로그램.
Arraylist, Collection 미사용. sorting은 TreeMap의 키값 정렬을 활용하여,
TreeMap key에 HashMap value를 넣고, 중복 value 가 있을경우 + 연산으로 중복 key 제거후 sorting
package main;
import java.util.Scanner;
import controller.HumanController;
public class mainClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HumanController humanController = new HumanController();
out: while (true) {
System.out.println("===== BaseballMember Manage =====");
System.out.println("1.선수추가 2.선수삭제 3.선수검색 4.선수수정\n5.데이터저장 6.방어율정렬 7.타율정렬 0.종료");
int choice = sc.nextInt();
switch (choice) {
case 1: // 선수 추가
humanController.baseballmemberAddOne();
break;
case 2: // 선수 삭제
humanController.delete();
break;
case 3: // 선수 검색
humanController.search();
break;
case 4: // 선수 수정
humanController.update();
break;
case 5: // 데이터 저장
humanController.saveData();
break;
case 6: // 방어율 내림차순 정렬
humanController.pitcherSorting();
break;
case 7: // 타율 내림차순 정렬
humanController.batterSorting();
break;
case 8: // 확인 출력
humanController.print();
break;
case 0: // 종료
break out;
default:
System.out.println("잘못입력하셨습니다.");
}
}
}
}
Controller main
package controller;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeMap;
import dto.Batter;
import dto.Human;
import dto.Pitcher;
import file.DataFile;
public class HumanController {
Scanner sc = new Scanner(System.in);
HashMap<Integer, Human> mapList;
DataFile data;
public HumanController() {
data = new DataFile("baseball");
mapList = data.readfile();
// Human m1 = new Pitcher();
// m1.setNumber(20);
// m1.setName("lee");
// m1.setAge(19);
// m1.setHeight(175.6);
// ((Pitcher) m1).setWin(14);
// ((Pitcher) m1).setLose(38);
// ((Pitcher) m1).setDef(0.2);
//
// Human m2 = new Pitcher();
// m2.setNumber(2);
// m2.setName("kim");
// m2.setAge(20);
// m2.setHeight(179.2);
// ((Pitcher) m2).setWin(17);
// ((Pitcher) m2).setLose(48);
// ((Pitcher) m2).setDef(0.3);
//
// Human m3 = new Batter();
// m3.setNumber(3);
// m3.setName("kang");
// m3.setAge(21);
// m3.setHeight(172.9);
// ((Batter) m3).setHit(158);
// ((Batter) m3).setBat(489);
// ((Batter) m3).setBatAvg(0.3);
//
// Human m4 = new Batter();
// m4.setNumber(4);
// m4.setName("ruru");
// m4.setAge(22);
// m4.setHeight(182.4);
// ((Batter) m4).setHit(15);
// ((Batter) m4).setBat(95);
// ((Batter) m4).setBatAvg(0.25);
//
// Human m5 = new Batter();
// m5.setNumber(5);
// m5.setName("TT");
// m5.setAge(18);
// m5.setHeight(185.1);
// ((Batter) m5).setHit(18);
// ((Batter) m5).setBat(136);
// ((Batter) m5).setBatAvg(0.44);
//
// mapList.put(m1.getNumber(), m1);
// mapList.put(m2.getNumber(), m2);
// mapList.put(m3.getNumber(), m3);
// mapList.put(m4.getNumber(), m4);
// mapList.put(m5.getNumber(), m5);
}
public void print() {
Iterator<Integer> print = mapList.keySet().iterator();
while (print.hasNext()) {
int key = print.next();
System.out.println(mapList.get(key).toString());
}
}
public int selectOne(int num) {
int key = -1;
Iterator<Integer> print = mapList.keySet().iterator();
while (print.hasNext()) {
key = print.next();
if (mapList.get(key).getNumber() == num) {
return key;
}
}
return key;
}
private Human choiceOne() {
System.out.println("1.투수 2.타자");
int choice = sc.nextInt();
if (choice == 1) {
Human m = new Pitcher();
return m;
} else if (choice == 2) {
Human m = new Batter();
return m;
}
return null;
}
public void baseballmemberAddOne() {
Human m = choiceOne();
if (m == null)
return;
if (m instanceof Pitcher) {
System.out.print("이름: ");
((Pitcher) m).setName(sc.next());
System.out.print("나이: ");
((Pitcher) m).setAge(sc.nextInt());
System.out.print("키: ");
((Pitcher) m).setHeight(sc.nextDouble());
System.out.print("승 수: ");
((Pitcher) m).setWin(sc.nextInt());
System.out.print("패 수: ");
((Pitcher) m).setLose(sc.nextInt());
System.out.print("방어율: ");
((Pitcher) m).setDef(sc.nextDouble());
System.out.print("등번호: ");
int number = sc.nextInt();
while (true) {
if (!mapList.containsKey(number)) {
m.setNumber(number);
break;
} else {
System.out.print("사용하고 있는 등번호 입니다.\n다시 입력하세요: ");
number = sc.nextInt();
continue;
}
}
mapList.put(m.getNumber(), m);
} else if (m instanceof Batter) {
System.out.print("이름: ");
((Batter) m).setName(sc.next());
System.out.print("나이: ");
((Batter) m).setAge(sc.nextInt());
System.out.print("키: ");
((Batter) m).setHeight(sc.nextDouble());
System.out.print("타수: ");
((Batter) m).setHit(sc.nextInt());
System.out.print("스윙수: ");
((Batter) m).setBat(sc.nextInt());
System.out.print("방어율: ");
((Batter) m).setBatAvg(sc.nextDouble());
System.out.print("등번호: ");
int number = sc.nextInt();
while (true) {
if (!mapList.containsKey(number)) {
m.setNumber(number);
break;
} else {
System.out.print("사용하고 있는 등번호 입니다.\n다시 입력하세요: ");
number = sc.nextInt();
continue;
}
}
mapList.put(m.getNumber(), m);
}
}
public void delete() {
System.out.println("등번호를 입력해주세요: ");
int number = sc.nextInt();
if (mapList.containsKey(number)) {
mapList.remove(number);
System.out.println(number + "번 선수가 삭제 되었습니다.");
} else {
System.out.println("없는 등번호입니다.");
}
}
public void search() {
System.out.println("등번호를 입력해주세요: ");
int number = sc.nextInt();
int one = selectOne(number);
if (one == -1) {
System.out.println("없는 등번호 입니다.");
return;
}
if (mapList.get(one) instanceof Pitcher) {
System.out.println(((Pitcher) mapList.get(one)).toString());
} else {
System.out.println(((Batter) mapList.get(one)).toString());
}
}
public void update() {
System.out.println("등번호를 입력해주세요: ");
int number = sc.nextInt();
if (mapList.containsKey(number)) {
Human m = mapList.get(number);
System.out.println("수정할 내용을 입력합니다: ");
if (m instanceof Pitcher) {
System.out.println(m.getName() + "투수의 정보를 수정합니다.");
System.out.print("승 수: ");
((Pitcher) m).setWin(sc.nextInt());
System.out.print("패 수: ");
((Pitcher) m).setLose(sc.nextInt());
} else if (m instanceof Batter) {
System.out.println(m.getName() + "타자의 정보를 수정합니다.");
System.out.print("타수: ");
((Batter) m).setHit(sc.nextInt());
System.out.print("스윙수: ");
((Batter) m).setBat(sc.nextInt());
}
mapList.replace(number, m);
} else {
System.out.println("없는 등번호입니다.");
}
}
public void pitcherSorting() {
// 정렬을 위한 TreeMap 선언
TreeMap<Double, Human> sort = new TreeMap<Double, Human>();
// TreeMap key에 mapList의 value를 찾아 TreeMap에 담는 과정.
for (Integer key : mapList.keySet()) {
if (mapList.get(key) instanceof Pitcher) { // 해당하는 클래스만 담음.
if (sort.containsKey(((Pitcher) mapList.get(key)).getDef())) {
sort.put(((Pitcher) mapList.get(key)).getDef() + 0.00001, mapList.get(key));
}else {
sort.put(((Pitcher) mapList.get(key)).getDef(), mapList.get(key));
}
}
}
Iterator<Double> sorting = sort.descendingKeySet().iterator(); // 내림차순 정렬
while (sorting.hasNext()) {
Double key = sorting.next();
System.out.println(sort.get(key).toString()); // 출력
} // key 값은 중복이 되지 않음으로 이런식으로 value값을 정렬 하면 중복된 값들은 하나만 남겨지는 문제가
// 발생하므로 sort.put(((Pitcher) mapList.get(key)).getDef() + 0.00001, mapList.get(key)); 을 적용
// 키값중복을 방지하였다.
}
public void batterSorting() {
TreeMap<Double, Human> sort = new TreeMap<Double, Human>();
for (Integer key : mapList.keySet()) {
if (mapList.get(key) instanceof Batter) {
if (sort.containsKey(((Batter) mapList.get(key)).getBatAvg())) {
sort.put(((Batter) mapList.get(key)).getBatAvg() + 0.00001, mapList.get(key));
}else {
sort.put(((Batter) mapList.get(key)).getBatAvg(), mapList.get(key));
}
}
}
Iterator<Double> sorting = sort.descendingKeySet().iterator();
while (sorting.hasNext()) {
Double key = sorting.next();
System.out.println(sort.get(key).toString());
}
}
public void saveData() {
String[] datas = new String[mapList.size()];
int i = 0;
for (Integer key : mapList.keySet()) {
Human m = mapList.get(key);
if (m instanceof Pitcher) {
datas[i] = ((Pitcher) m).toString();
i++;
} else if (m instanceof Batter) {
datas[i] = ((Batter) m).toString();
i++;
}
data.writefile(datas);
}
System.out.println("데이터를 성공적으로 저장했습니다.");
}
}
File Input Output
package file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import dto.Batter;
import dto.Human;
import dto.Pitcher;
public class DataFile {
private String fileName;
private File file;
public DataFile(String filename) {
this.fileName = filename;
file = new File("c:\\JavaFilePrint\\" + filename + ".txt");
createfile();
}
private void createfile() {
try {
if (file.createNewFile()) {
System.out.println("파일 생성 성공!");
} else {
System.out.println("파일 생성 실패");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void writefile(String[] datas) {
PrintWriter pw;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
for (int i = 0; i < datas.length; i++) {
pw.println(datas[i]);
}
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public HashMap<Integer, Human> readfile() {
HashMap<Integer, Human> map = new HashMap<Integer, Human>();
try {
if (checkFile(file)) {
BufferedReader br = new BufferedReader(new FileReader(file));
String str = "";
Human human = null;
while ((str = br.readLine()) != null) {
String[] split = str.split("-");
if (Integer.parseInt(split[7]) == 0) {
human = new Pitcher(Integer.parseInt(split[0]), split[1], Integer.parseInt(split[2]),
Double.parseDouble(split[3]), Integer.parseInt(split[4]), Integer.parseInt(split[5]),
Double.parseDouble(split[6]), Integer.parseInt(split[7]));
map.put(Integer.parseInt(split[0]), human);
} else {
human = new Batter(Integer.parseInt(split[0]), split[1], Integer.parseInt(split[2]),
Double.parseDouble(split[3]), Integer.parseInt(split[4]), Integer.parseInt(split[5]),
Double.parseDouble(split[6]), Integer.parseInt(split[7]));
map.put(Integer.parseInt(split[0]), human);
}
}
br.close();
} else {
System.out.println("파일이 없거나 읽을 수 없습니다.");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
public boolean checkFile(File f) {
if (f.exists()) {
if (f.isFile() && f.canRead()) {
return true;
}
}
return false;
}
}
HumanDto
package dto;
public class Human {
private int number;
private String name;
private int age;
private double height;
public Human() {
}
public Human(int number, String name, int age, double height) {
this.number = number;
this.name = name;
this.age = age;
this.height = height;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public String toString() {
return number + "-" + name + "-" + age + "-" + height;
}
}
PitcherDto extends HumanDto
package dto;
public class Pitcher extends Human {
private int win;
private int lose;
private double def;
private static int num = 0;
public Pitcher() {
}
public Pitcher(int number, String name, int age, double height, int win, int lose, double def, int num) {
super(number, name, age, height);
this.win = win;
this.lose = lose;
this.def = def;
this.num = num;
}
public int getWin() {
return win;
}
public void setWin(int win) {
this.win = win;
}
public int getLose() {
return lose;
}
public void setLose(int lose) {
this.lose = lose;
}
public double getDef() {
return def;
}
public void setDef(double def) {
this.def = def;
}
@Override
public String toString() {
return super.toString() + "-" + win + "-" + lose + "-" + def + "-" + num;
}
}
BatterDto extends HumanDto
package dto;
public class Batter extends Human {
private int bat;
private int hit;
private double batAvg;
private static int num = 1;
public Batter() {
}
public Batter(int number, String name, int age, double height, int bat, int hit, double batAvg, int num) {
super(number, name, age, height);
this.bat = bat;
this.hit = hit;
this.batAvg = batAvg;
this.num = num;
}
public int getBat() {
return bat;
}
public void setBat(int bat) {
this.bat = bat;
}
public int getHit() {
return hit;
}
public void setHit(int hit) {
this.hit = hit;
}
public double getBatAvg() {
return batAvg;
}
public void setBatAvg(double batAvg) {
this.batAvg = batAvg;
}
@Override
public String toString() {
return super.toString() + "-" + bat + "-" + hit + "-" + batAvg + "-" + num;
}
}
'Toy' 카테고리의 다른 글
호텔 예약 웹사이트 (Hotel BuleMoon) 세미프로젝트 (0) | 2020.03.02 |
---|---|
Coffee Order Program(kiosk) (0) | 2020.01.02 |