Daily coding
Java Basic : day 11 - Example01: Baseball 선수정보 입력(HashMap, TreeMap사용) 본문
Language/Java_basic
Java Basic : day 11 - Example01: Baseball 선수정보 입력(HashMap, TreeMap사용)
sunnnkim 2019. 12. 2. 20:03
1. 부모클래스 Human
package day11.Example_project;
public class Human {
//(부모) human class : id, name, age, height(double)
protected int number;
private String name;
private int age;
private double height;
public Human() {
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Human(String name, int age, double height) {
this.name = name;
this.age= age;
this.height = height;
}
// 데이터 사이즈
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;
}
}
2. Human 상속받은 자녀클래스 Pitcher ( 투수 )
package day11.Example_project;
public class Pitcher extends Human{
//(자식) pitcher : win, lose, defence(double)
// private static int id;
private int win;
private int lose;
private double defence;
public Pitcher() {
// Pitcher.id++;
}
public Pitcher(String name, int age, double height, int win, int lose, double defence) {
super(name,age,height);
this.win = win;
this.lose= lose;
this.defence = defence;
}
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 getDefence() {
return defence;
}
public void setDefence(double defence) {
this.defence = defence;
}
@Override
public String toString() {
return super.toString()+"-" + win +"-" + lose+"-" + defence;
}
}
3. Human 상속받은 자녀클래스 Batter ( 타자 )
package day11.Example_project;
public class Batter extends Human{
private static int id;
//(자식) batter : bat, hit, batAvg(double)
private int bat;
private int hit;
private double batAvg;
public Batter() {
Batter.id++;
this.number = Batter.id + 2000;
}
public Batter(String name, int age, double height, int bat, int hit, double batAvg) {
super(name, age, height);
this.bat = bat;
this.hit = hit;
this.batAvg = batAvg;
Batter.id++;
this.number = Batter.id + 2000;
}
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;
}
}
4. DAO
package day11.Example_project;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeMap;
public class BaseballMemberDAO {
// TODO: field
HashMap<String, Human> blist;
DataClass fData ;
Scanner sc = new Scanner(System.in);
public BaseballMemberDAO() throws Exception {
// 기본 데이터 추가
fData = new DataClass("Baseball");
if(fData.readFile() == null) blist = new HashMap<String, Human>();
else blist = fData.readFile();
}
//TODO: CRUD
// 추가
public void insert(Human h) {
blist.put(h.getName(),h);
}
// 삭제
public void delete(String name) {
blist.remove(name);
}
// 검색 (Value 반환)
public Human select() {
String name = search();
if(name == null) return null;
Human h = blist.get(name);
return h;
}
// 수정
public void update(Human h) {
blist.replace(h.getName(), h);
}
// TODO : 데이터 검색
public String search() {
System.out.print("검색할 이름: ");
String name = sc.next();
if(blist.containsKey(name))
return name;
return null;
}
// 프린트
public void printAll() {
System.out.println("< 전체 선수명단 >");
TreeMap<Integer, Human> sortId = sortById();
Iterator<Integer> it = sortId.keySet().iterator();
while(it.hasNext()) {
Integer key = it.next();
System.out.println(key);
System.out.println(sortId.get(key).toString());
}
}
//TODO: files
// 데이터저장
public void dataSave() throws Exception {
System.out.println("< 파일로 저장하기 : (경로= d:\\BaseballMember\\) ");
fData.writeFile(blist);
System.out.println("파일 저장완료");
}
// 아이디 값으로 정렬하기
public TreeMap<Integer,Human> sortById() {
TreeMap<Integer,Human> sortId = new TreeMap<Integer, Human>();
Iterator<String> it = blist.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
sortId.put(blist.get(key).getNumber(),blist.get(key));
}
return sortId;
}
//TODO: sorting
// 정렬
public TreeMap<Double, Human> sorting(int i) {
// 투수 : 방어율
TreeMap<Double, Human> sortDefence = new TreeMap<Double, Human>();
// 타자 : 타율
TreeMap<Double, Human> sortBatAvg = new TreeMap<Double, Human>();
Iterator<String> it = blist.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
if(blist.get(key) instanceof Pitcher) {
double d = ((Pitcher)blist.get(key)).getDefence();
while(sortDefence.containsKey(d)) {
d+=0.011;
}
sortDefence.put(d, blist.get(key));
}
else{
double d = ((Batter)blist.get(key)).getBatAvg();
while(sortBatAvg.containsKey(d)) {
d+=0.011;
}
sortBatAvg.put(d, blist.get(key));
}
}
if( i ==1 ) { // 투수 방어율 보기
return sortDefence;
}else if(i ==2) {
return sortBatAvg;
}else {
return null;
}
}
public void userSorting() {
System.out.println("< 정렬하기 >");
System.out.println("1.투수 방어율 순으로 보기");
System.out.println("2.타자 타율 순으로 보기");
System.out.print(">> ");
int choice;
try {
choice = sc.nextInt();
} catch (Exception e) {
choice = -1;
}
TreeMap<Double, Human> result = sorting(choice);
if(result == null) System.out.println("잘못 누르셨습니다.");
else {
System.out.println("< 선수 명단 >");
Iterator<Double> it = result.descendingKeySet().iterator();
while(it.hasNext()) {
double key = it.next();
System.out.println(result.get(key).toString());
}
}
}
// TODO: User Interface
// 유저메뉴
// 투수(pitcher) : 아이디(자동추가), 이름, 나이, 키(d), 승, 패, 방어율
// 타자(batter) : 아이디(자동추가), 이름, 나이, 키(d), 던진횟수, 맞힌 횟수, 타율
public void UserInsert() {
System.out.println("< 선수 추가하기 >");
System.out.println("1.타자 추가 2. 투수 추가");
int choice;
try {
choice = sc.nextInt();
} catch (Exception e) {
choice = -1;
}
Human h;
if(choice == 1) { // batter
h = new Batter();
System.out.print("이름: ");
h.setName(sc.next());
System.out.print("나이: ");
h.setAge(sc.nextInt());
System.out.print("키: ");
h.setHeight(sc.nextDouble());
System.out.print("친 횟수: ");
((Batter)h).setBat(sc.nextInt());
System.out.print("유효타: ");
((Batter)h).setHit(sc.nextInt());
System.out.print("타율: ");
((Batter)h).setBatAvg(sc.nextDouble());
}
else if(choice == 2) { // pitcher : 아이디(자동추가), 이름, 나이, 키(d), 승, 패, 방어율
h = new Pitcher();
System.out.print("이름: ");
h.setName(sc.next());
System.out.print("나이: ");
h.setAge(sc.nextInt());
System.out.print("키: ");
h.setHeight(sc.nextDouble());
System.out.print("승리 횟수: ");
((Pitcher)h).setWin(sc.nextInt());
System.out.print("패 횟수: ");
((Pitcher)h).setLose(sc.nextInt());
System.out.print("방어율: ");
((Pitcher)h).setDefence(sc.nextDouble());
}
else {
h=null;
System.out.println("잘못입력했습니다.");
return;
}
if(blist.containsKey(h.getName())) {
System.out.println("이미 있는 이름입니다.");
}else insert(h);
}
// User Delete
public void userDelete() {
System.out.println("< 선수데이터 삭제 >");
String name = search();
if(name!=null) {
System.out.println(name+ " 선수의 정보를 삭제했습니다.");
delete(name);
}
else System.out.println("선수가 없습니다.");
}
// User Select
public void userSelect() {
String name = search();
if(name!=null) {
System.out.println("< 선수 정보 >");
System.out.println(blist.get(name));
}else {
System.out.println("선수가 없습니다.");
}
}
// User Update
public void userUpdate() {
String name = search();
if(name!=null){
System.out.println("< "+ name +" 선수 정보수정 >");
System.out.println("이름: " + name);
if(blist.get(name) instanceof Pitcher) { // 투수일 때
// 나이: 30, 키: 172.9, 10승 6패, 방어율: 0.55
Pitcher p = (Pitcher) blist.get(name);
System.out.print("나이: ");
p.setAge(sc.nextInt());
System.out.print("키: ");
p.setHeight(sc.nextDouble());
System.out.print("승리 횟수: ");
p.setWin(sc.nextInt());
System.out.print("패 횟수: ");
p.setLose(sc.nextInt());
System.out.print("방어율: ");
p.setDefence(sc.nextDouble());
}else { // 타자일 때
// [이대호(타자)] 나이: 25, 키: 179.1, 25타석 10타수, 타율: 0.4
Batter b = (Batter)blist.get(name);
System.out.print("나이: ");
b.setAge(sc.nextInt());
System.out.print("키: ");
b.setHeight(sc.nextDouble());
System.out.print("친 횟수: ");
b.setBat(sc.nextInt());
System.out.print("유효타: ");
b.setHit(sc.nextInt());
System.out.print("타율: ");
b.setBatAvg(sc.nextDouble());
}
}else {
System.out.println("선수가 없습니다.");
}
}
}
5. mainClass
package day11.Example_project;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) throws Exception {
// Baseball Member
/*
(부모) human class : id, name, age, height(double)
(자식) pitcher : win, lose, defence(double),
(자식) batter : bat, hit, batAvg(double)
baseball member : id, pitter/batter
- 선수추가 / 삭제 / 검색 / 수정 / 데이터 저장(file)
- 방어율 또는 타율로 정렬
- 조건: Map 사용(hash/tree 둘 중 하나 사용)
- human의 id: 중복되면 안됨, 자동으로 나열되도록 하기
-
*/
BaseballMemberDAO blist = new BaseballMemberDAO();
Scanner sc = new Scanner(System.in);
System.out.println("< Baseball Member >");
while(true) {
System.out.println("1. 선수 추가하기");
System.out.println("2. 선수 삭제하기");
System.out.println("3. 선수 검색하기");
System.out.println("4. 선수 수정하기");
System.out.println("5. 선수 전체보기");
System.out.println("6. 타율/방어율 순으로 보기");
System.out.println("7. 파일로 저장하기");
System.out.println("0. 종료하기");
System.out.print(">> ");
int choice;
try {
choice= sc.nextInt();
} catch (Exception e) {
choice = -1;
}
if(choice == 1) {
//추가
blist.UserInsert();
}else if(choice == 2) {
//삭제
blist.userDelete();
}else if(choice == 3) {
// 검색
blist.userSelect();
}else if(choice == 4) {
// 수정
blist.userUpdate();
}else if(choice == 5) {
// 전체보기
blist.printAll();
}else if(choice == 6) {
// 타율/방어율 순으로 보기
blist.userSorting();
}else if(choice == 7) {
// 파일로 저장
blist.dataSave();
}else if(choice == 0) {
System.out.println("종료합니다.");
break;
}else {
System.out.println("잘못 누르셨습니다.");
}
}}
}
'Language > Java_basic' 카테고리의 다른 글
Java Basic : day 12 - Example01: Baseball 선수정보 입력(HashMap, TreeMap사용) 버전 2 (0) | 2019.12.04 |
---|---|
Java Basic : day 12 - Singleton 싱글턴 패턴 (0) | 2019.12.04 |
Java Basic : day 10 - LinkedList 링크드리스트 (0) | 2019.12.02 |
Java Basic : day 11 - Interface 인터페이스 (0) | 2019.12.02 |
Java Basic : day 11 - Abstract 추상 클래스 (0) | 2019.12.02 |