Daily coding
Java Basic : day 12 - Example01: Baseball 선수정보 입력(HashMap, TreeMap사용) 버전 2 본문
Language/Java_basic
Java Basic : day 12 - Example01: Baseball 선수정보 입력(HashMap, TreeMap사용) 버전 2
sunnnkim 2019. 12. 4. 19:16
(강사님 답)
Human(부모클래스)
package day12.ExampleAnswer.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;
}
public void infomation() {
System.out.println("이름:" + name);
System.out.println("나이:" + age);
System.out.println("신장:" + height);
}
@Override
public String toString() {
return number + "-" + name + "-" + age + "-" + height;
}
}
2. Pitcher
package day12.ExampleAnswer.dto;
public class Pitcher extends Human {
private int win;
private int lose;
private double defence;
// 생성자
public Pitcher() {
super();
}
public Pitcher(int number, String name, int age, double height,int win, int lose, double defence) {
super(number, name, age, height);
this.win = win;
this.lose = lose;
this.defence = defence;
}
// getter / setter
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;
}
public void infomation() {
super.infomation();
System.out.println("승: "+ win);
System.out.println("패: "+ lose);
System.out.println("방어율: "+ defence);
}
@Override
// DB에 입력할 때 toString 사용해서 토큰까지 넣음
public String toString() {
return super.toString() + "-" + win + "-" + lose + "-" + defence;
}
}
3. Batter
package day12.ExampleAnswer.dto;
public class Batter extends Human{
private int batcount;
private int hitcount;
private double hitAvg;
public Batter() {
super();
// TODO Auto-generated constructor stub
}
public Batter(int number, String name, int age, double height, int batcount, int hitcount, double hitAvg) {
super(number, name, age, height);
this.batcount = batcount;
this.hitcount = hitcount;
this.hitAvg = hitAvg;
}
public int getBatcount() {
return batcount;
}
public void setBatcount(int batcount) {
this.batcount = batcount;
}
public int getHitcount() {
return hitcount;
}
public void setHitcount(int hitcount) {
this.hitcount = hitcount;
}
public double getHitAvg() {
return hitAvg;
}
public void setHitAvg(double hitAvg) {
this.hitAvg = hitAvg;
}
public void infomation() {
// TODO Auto-generated method stub
super.infomation();
System.out.println("타수: "+ batcount);
System.out.println("안타수: "+ hitcount);
System.out.println("타율: "+ hitAvg);
}
@Override
public String toString() {
return super.toString() +"-" + batcount + "-" + hitcount + "-" + hitAvg;
}
}
DAO
package day12.ExampleAnswer.dao;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeMap;
import day12.ExampleAnswer.dto.Batter;
import day12.ExampleAnswer.dto.Human;
import day12.ExampleAnswer.dto.Pitcher;
public class MemberDao {
Scanner sc = new Scanner(System.in);
private HashMap<String, Human> map = new HashMap<String,Human>();
DataFile dataCls;
private int memNumber; // sequence number : 아이디 값 주기
public MemberDao() throws Exception{
map = new HashMap<String, Human>();
dataCls = new DataFile("Baseball");
dataCls.createfile();
map = dataCls.readFile();
if(map.size()>0) {
Iterator<String> it = map.keySet().iterator();
int lastNum = 0;
while(it.hasNext()) {
String key = it.next();
Human h = map.get(key);
int lastMemNum = h.getNumber();
if(lastMemNum >= 2000 ) // 2000번 이상 일경우 -1000하기
lastMemNum -= 1000;
if(lastNum < lastMemNum) lastNum = lastMemNum;
}
memNumber = lastNum+1;
}
// 계산 해줄 거 필요함
}
public void insert() {
System.out.println(">> 선수등록");
System.out.println("투수(1) 타자(2) 등록하고 싶은 포지션을 입력해주십시오.");
System.out.print(">>>>> ");
int choice;
choice = sc.nextInt();
Human human = null;
System.out.print("이름 : ");
String name = sc.next();
System.out.print("나이 : ");
int age = sc.nextInt();
System.out.print("신장 : ");
double height = sc.nextDouble();
if(choice == 1) { // 투수
System.out.print("승 : ");
int win = sc.nextInt();
System.out.print("패 : ");
int lose = sc.nextInt();
System.out.print("방어율 : ");
double defence = sc.nextDouble();
human = new Pitcher(memNumber, name, age, height, win, lose, defence);
}else if(choice == 2) { // 타자
System.out.print("타수 : ");
int batcount = sc.nextInt();
System.out.print("안타수 : ");
int hitcount = sc.nextInt();
System.out.print("타율 : ");
double hitAvg = sc.nextDouble();
human = new Batter(memNumber+1000, name, age, height, batcount, hitcount, hitAvg);
}
// 선수등록 :1000, 2001, 2002, 1003
// map에 추가
map.put(human.getName(), human);
memNumber++;
}
public void delete() {
System.out.println("방출하고 싶은 선수명을 입력해주십시오.");
System.out.print(">> ");
String name = sc.next();
Human h = map.get(name);
if(h == null || h.getName().equals("")) {
System.out.println("데이터를 찾을 수 없습니다.");
return;
}
h = map.get(name);
System.out.println(h.getName()+" 선수의 데이터가 삭제되었습니다.");
map.remove(name);
}
public void select() {
System.out.println("검색하고 싶은 선수명을 입력해주십시오.");
System.out.print(">> ");
String name = sc.next();
Human h = map.get(name);
if(h == null || h.getName().equals("")) {
System.out.println("데이터를 찾을 수 없습니다.");
return;
}
System.out.println("검색된 선수입니다.");
h.infomation();
}
public void update() {
System.out.println("수정하고 싶은 선수명을 입력해주십시오.");
System.out.print(">> ");
String name = sc.next();
Human h = map.get(name);
if(h == null || h.getName().equals("")) {
System.out.println("데이터를 찾을 수 없습니다.");
return;
}
System.out.println("수정할 데이터를 입력하시오.");
if( h.getNumber() < 2000 ) { // 투수
Pitcher p = (Pitcher)h;
System.out.println("승 : ");
int win = sc.nextInt();
System.out.println("패 : ");
int lose = sc.nextInt();
System.out.println("방어율 : ");
double defence = sc.nextDouble();
p.setWin(win);
p.setLose(lose);
p.setDefence(defence);
}else { // 타자
Batter b = (Batter)h;
System.out.println("타수 : ");
int batcount = sc.nextInt();
System.out.println("안타수 : ");
int hitcount = sc.nextInt();
System.out.println("타율 : ");
double hitAvg = sc.nextDouble();
b.setBatcount(batcount);
b.setHitcount(hitcount);
b.setHitAvg(hitAvg);
}
System.out.println("데이터를 수정했습니다.");
}
public void allPrint() {
Iterator<String> it = map.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
System.out.println(map.get(key).toString());
}
}
public void memberSorting () {
HashMap<String,Human> hashMap = new HashMap<String, Human>();
Iterator<String> it = map.keySet().iterator();
int w = 0; // 같은 키 값이 들어가지 않도록 할 변수
while(it.hasNext()) {
String key = it.next();
Human h = map.get(key);
if(h instanceof Pitcher ) {
Pitcher p =(Pitcher)h;
hashMap.put( p.getDefence() + "" + w, p);
w++;
}
}
TreeMap<String,Human> tMap = new TreeMap<String, Human> (hashMap);
Iterator<String> updownIt = tMap.keySet().iterator();
while(updownIt.hasNext()) {
String key = updownIt.next();
System.out.print("key: " + key + " ");
Human h = tMap.get(key);
System.out.println(h.toString());
}
}
// 파일 저장
public void saveData() {
String arrStr[]= new String[map.size()];
Iterator<String> it = map.keySet().iterator();
int w=0;
while(it.hasNext()) {
String key = it.next();
Human h = map.get(key);
arrStr[w] = h.toString();
w++;
}
dataCls.writeFile(arrStr);
}
}
File 입출력 클래스
package day12.ExampleAnswer.dao;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import day12.ExampleAnswer.dto.Batter;
import day12.ExampleAnswer.dto.Human;
import day12.ExampleAnswer.dto.Pitcher;
public class DataFile {
private File file;
public DataFile(String filename) {
file = new File("d:\\tmp\\"+filename +".txt");
}
public void createfile() {
try {
if(file.createNewFile()) {
System.out.println("파일 생성 성공!");
}else{
System.out.println("파일 생성 실패");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile(String data[]) {
try {
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
for (int i = 0; i < data.length; i++) {
pw.println(data[i]);
}
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("파일에 성공적으로 기입했습니다.");
}
// 파일 생성해서 dao에 바로 넘겨주기
public HashMap<String, Human> readFile() throws Exception{
HashMap<String, Human> map = new HashMap<String, Human>();
if(checkBeforeReadFile(file)) {
BufferedReader br = new BufferedReader(new FileReader(file));
String str = "";
Human human = null;
while((str= br.readLine())!=null) {
String splits[] = str.split("-");
// 투수
if(Integer.parseInt(splits[0]) < 2000) {
human = new Pitcher(Integer.parseInt(splits[0]),
splits[1],
Integer.parseInt(splits[2]),
Double.parseDouble(splits[3]),
Integer.parseInt(splits[4]),
Integer.parseInt(splits[5]),
Double.parseDouble(splits[6]));
map.put(human.getName(), human);
}
// 타자
else {
human = new Batter(Integer.parseInt(splits[0]),
splits[1],
Integer.parseInt(splits[2]),
Double.parseDouble(splits[3]),
Integer.parseInt(splits[4]),
Integer.parseInt(splits[5]),
Double.parseDouble(splits[6]));
map.put(human.getName(), human);
}
}
}
else {
System.out.println("파일이 없거나 읽을 수 없습니다.");
return null;
}
return map;
}
// 파일이 있고 읽을 수 있는 지 확인용 메소드
public boolean checkBeforeReadFile(File f) {
if(f.exists())
if(f.isFile() && f.canRead())
return true;
return false;
}
}
MainClass는 알아서 생성하라고 함
'Language > Java_basic' 카테고리의 다른 글
Java Basic : day 13 - Factory Pattern 팩토리패턴 (0) | 2019.12.04 |
---|---|
Java Basic : day 13 - Calendar 캘린더 클래스 (0) | 2019.12.04 |
Java Basic : day 12 - Singleton 싱글턴 패턴 (0) | 2019.12.04 |
Java Basic : day 11 - Example01: Baseball 선수정보 입력(HashMap, TreeMap사용) (0) | 2019.12.02 |
Java Basic : day 10 - LinkedList 링크드리스트 (0) | 2019.12.02 |