# 19. Java 18일차(230908) [국비교육]

brand_mins·2023년 9월 8일

Java

목록 보기
19/47

1. 시간 관련 클래스

(1) LocalDateTime 클래스

1. 시간 관련 예제
import java.time.LocalDateTime;

public class LocalDateTimeExample {

	public static void main(String[] args) {
		// 현재 날짜와 시간을 LocalDateTime 객체로 받기
		LocalDateTime now = LocalDateTime.now();
		
		// LocalDateTIme 객체를 문자열로 출력
		System.out.println("현재 날짜와 시간: " + now.toString());
		
		// LocalDateTime 객체에서 년,월,일,시,분,초 값 추출하기
		int year = now.getYear();
		int month = now.getMonthValue();
		int day = now.getDayOfMonth();
		int hour = now.getHour();
		int minute = now.getMinute();
		int second = now.getSecond();
		
		// 추출한 값 출력
		System.out.println("년: " + year);
		System.out.println("월: " + month);
		System.out.println("일: " + day);
		System.out.println("시: " + hour);
		System.out.println("분: " + minute);
		System.out.println("초: " + second);

	}

}

2. 현재 시간을 얻어오는 방법
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println(formattedDateTime);

3. 문자열을 시간 객체로 만들고 시간 객체를 원하는 문자열로 만드는 코드
String strDateTime = "2023-09-08T12:30:00";
LocalDateTime dateTime = LocalDateTime.parse(strDateTime);

4. "2023-09-08T12:30:00"LocalDateTime 객체로 변환
strDateTime = "2023-09-08 10:40:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
dateTime = LocalDateTime.parse(strDateTime,formatter);

(2) Duration 클래스

  • 두 LocalDateTime 객체의 시간 차이를 구하는 방법
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;

public class LocalEx02 {

	public static void main(String[] args) {
		// start시간이 end시간보다 앞선 시간이여야 한다.
		// 1. Period는 년월일을 계산하고 Duration은 시분초를 계산한다.
		// 2. Period는 시분초를 계산되지 않고 잘려진다음 계산한다.
		// LocalDateTime startDateTime = LocalDateTime.of(2023,9,8,11,0,0);
		// LocalDateTime endDateTime = LocalDateTime.of(2023,9,8,17,30,0);
		// 년: 0년, 월: 0개월, 일:1일 // 시분초가 포함된다면 0일이 되어야 하는데 1일로 출력
		// 일: 0시간:9시간, 분:30분, 초:20초
		// 3. Duration은 시,분,초 차이 계산한다. 일도 지원하긴 하지만 시분초와 연계되어 연산되지 않는다.
		// 다음 예제에서 연계된다면 일은 2시간은 23으로 출력되어야 하지만 toHours()는 71로 출력.
		LocalDateTime startDateTime = LocalDateTime.of(2023, 9,8,11,0,0);
		LocalDateTime endDateTime = LocalDateTime.of(2023,9,8,17,30,0);
			// Period 객체를 사용하여 년,월,일 계산
			Period period = Period.between(startDateTime.toLocalDate(), endDateTime.toLocalDate());
			int years = period.getYears();
			int months = period.getMonths();
			int days = period.getDays();
			// Duration 객체를 사용하여 시,분,초 계산
			Duration duration = Duration.between(startDateTime, endDateTime);
			long diffDays = duration.toDays();
			long hours = duration.toHours();
			long minutes = duration.toMinutesPart();
			long seconds = duration.toSecondsPart();
			System.out.println("년:" + years + "년, 월:" + months + "개월, 일:" + days + "일");
			System.out.println("일:" + diffDays+"시간:"+hours+":"
			+(hours-diffDays*24) + "시간, 분:"+ minutes + "분, 초: " + seconds + "초");

	}

}

(3) ChronoUnit 클래스

  • 두 시간의 차이를 시,분,초 하나를 얻고자 할때 사용함.
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalEx03 {

	public static void main(String[] args) {
		LocalDateTime dt1 = LocalDateTime.of(2023, 9,8,11,16,0);
		LocalDateTime dt2 = LocalDateTime.of(2023, 9,8,11,50,0);
		
		long hours = ChronoUnit.HOURS.between(dt1, dt2);
		long minutes = ChronoUnit.MINUTES.between(dt1, dt2);
		long seconds = ChronoUnit.SECONDS.between(dt1, dt2);
		long days = ChronoUnit.DAYS.between(dt1, dt2);
		
		System.out.println("두 시간의 차이(시): " + hours);
		System.out.println("두 시간의 차이(분): " + minutes);
		System.out.println("두 시간의 차이(초): " + seconds);
		System.out.println("두 시간의 차이(일): " + days);

	}

}
- 시간 연산하는 문제 구현
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalEx04 {

	public static void main(String[] args) {
		LocalDateTime now = LocalDateTime.now();
		LocalDateTime plusOneDay = now.plusDays(1);
		LocalDateTime plusTwoHours = now.plusHours(2);
		LocalDateTime plusTenMinutes = now.plusMinutes(10);
		LocalDateTime plusOneMonth = now.plusMonths(1);
		LocalDateTime plusOneYearOneMonth = now.plusYears(1).plusMonths(1);
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		
		System.out.println("현재 시간: " + now.format(formatter));
		System.out.println("하루 뒤: " + plusOneDay.format(formatter));
		System.out.println("두 시간 뒤: " + plusTwoHours.format(formatter));
		System.out.println("10분 뒤: " + plusTenMinutes.format(formatter));
		System.out.println("1달 뒤: " + plusOneMonth.format(formatter));
		System.out.println("1년 1개월 뒤: " + plusOneYearOneMonth.format(formatter));
		
		int dayOfMonth = now.getDayOfMonth();
		int hour = now.getHour();
		int minute = now.getMinute();
		
		System.out.println("현재 날짜: " + dayOfMonth);
		System.out.println("현재 시간: " + hour);
		System.out.println("현재 분: " + minute);

	}

}
++ 추가내용: 이것이 자바다(교재)

2. 추상 클래스

  • 추상 메소드는 구현부가 없는 메소드를 의미함.
  • 추상 클래스는 구현부가 없어서 인스턴스로 생성할 수 없음.
  • 인스턴스를 생성하려면 자식클래스에서 추상메소드들을 모두 재정의하여야만 함.
- 추상 메소드는 인터페이스를 위한 설명임.
- 간단히 추상메소드만 무엇인지 알고 넘어가기
abstract class Shape {
	private String color;
	// 추상 메소드 선언
	public abstract double getArea();
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
}
// 추상 클래스 Shape를 상속받은 하위 클래스 Rectangle
class Rectangle extends Shape {
	private double width;
	private double height;
	public Rectangle(double width, double height) {
		this.width = width;
		this.height = height;
	}
	// 추상 메소드 구현
	@Override
	public double getArea() {
		return width * height;
	}
}

public class AbsEx1 {

	public static void main(String[] args) {
		Rectangle rectangle = new Rectangle(5.0,10.0);
		rectangle.setColor("Red");
		System.out.println("색상: " + rectangle.getColor());
		System.out.println("넓이: " + rectangle.getArea());
		// Shape shape1 = new Shape(); 추상 클래스 생성x
		Shape shape1 = new Rectangle(5.0,10.0);
		Shape shape2 = new Circle(7.0);
		shape1.setColor("Red");
		System.out.println("색상: " +shape1.getColor());
		System.out.println("넓이: " + shape1.getArea());
		shape2.setColor("Blue");
		System.out.println("색상: " +shape2.getColor());
		System.out.println("넓이: " + shape2.getArea());

	}

}
++ 추가내용: 이것이 자바다(교재)
public interface RemoteControl {
	// 상수 필드
    int MIN_VOLUME = 10;
    int MAX_VOLUME = 0;
    
    // 추상 메소드
    void turnOn();
    void turnOff();
    void setVolume(int volume);
}

class TeleVision implements RemoteControl {
	// 필드
    private int volume;
    
    // turnOn 추상메소드
    @Override
    public void turnOn() {
    	System.out.println("TV를 켭니다");
    }
    
    @Override
    public void turnOff() {
    	System.out.println("TV를 끕니다");
    }
    
    @Override
    public void setVolume(int volume) {
    	if(volume>RemoteControl.MAX_VOLUME) {
        	this.volume = RemoteControl.MAX_VOLUME;
        } else if(volume < RemoteControl.MIN_VOLUME {
        	this.volume = RemoteControl.MIN_VOLUME;
        } else {
        	this.volume = volume;
        }
        System.out.println("현재 TV 볼륨: " + this.volume);
        }
}

class Audio implements RemoteControl {
	// 필드
    private int volume;
    
    @Override
    public void turnOn() {
    	System.out.println("TV를 켭니다");
    }
    
    @Override
    public void turnOff() {
    	System.out.println("TV를 끕니다");
    }
    
    @Override
    public void setVolume(int volume) {
    	if(volume>RemoteControl.MAX_VOLUME) {
        	this.volume = RemoteControl.MAX_VOLUME;
        } else if(volume < RemoteControl.MIN_VOLUME {
        	this.volume = RemoteControl.MIN_VOLUME;
        } else {
        	this.volume = volume;
        }
        System.out.println("현재 Audio 볼륨: " + this.volume);
        }
}

public class RemoteControlExample {
	public static void main(String[] args) {
    	// 인터페이스 변수 선언
        RemoteControl rc;
        
        // Television 객체를 생성하고 인터페이스 변수에 선언
        rc = new Television();
        rc.turnOn();
        rc.setVolume(5);
        rc.turnOff();
        
        // Audio 객체를 생성하고 인터페이스 변수에 선언
        rc = new Audio();
        rc.turnOn();
        rc.setVolume(5);
        rc.turnOff();
	}
}
++ 주의사항 ++
- 추상 메소드를 재정의할때 주의사항은 
인터페이스의 추상 메소드는 기본적으로 public 접근 제한을 갖기 때문에
public보다 더 낮은 접근 제한으로 재정의 할 수 없다.

3. 인터페이스

  • 구현부가 없는 추상 메소드로만 만들어진 클래스
  • 사용하려면 인터페이스를 상속한 자식 클래스에서 모든 메소드를 재정의 해야함.
  • 추상 메소드만으로 이루어져 있고 class 대신 interface라 기술함.
  • extends 대신에 implements 기술.
  • 다형성을 사용하기 위해 인터페이스 사용
  • 인터페이스는 다중상속 가능
import java.util.ArrayList;

interface Shape {
	public double getArea();
	public double getPerimeter();
}

class Circle implements Shape {
	private double radius;
	public Circle(double radius) {
		this.radius = radius;
	}
	public double getArea() {
		return Math.PI * radius * radius;
	}
	public double getPerimeter() {
		return 2 * Math.PI * radius;
	}
}

class Rectangle implements Shape {
	private double width;
	private double height;
	
	public Rectangle(double width, double height) {
		this.width = width;
		this.height = height;
	}
	
	public double getArea() {
		return width * height;
	}
	
	public double getPerimeter() {
		return 2 * (width + height);
	}
}

class Triangle implements Shape {
	private double side1;
	private double side2;
	private double side3;
	
	public Triangle(double side1, double side2, double side3) {
		this.side1 = side1;
		this.side2 = side2;
		this.side3 = side3;
	}
	
	public double getArea() {
		double s = (side1 + side2 + side3) / 2;
		return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
	}
	
	public double getPerimeter() {
		return side1 + side2 + side3;
	}
}

public class Main {
	public static void main(String[] args) {
		Shape[] shapes = new Shape[3];
		shapes[0] = new Circle(5);
		shapes[1] = new Rectangle(3,4);
		shapes[2] = new Triangle(3,4,5);
		
		for(Shape shape : shapes) {
			System.out.println("Area: " + shape.getArea() + ", Perimeter: " + shape.getPerimeter());
		}
		
		Shape s1 = new Circle(2);
		Shape s2 = new Rectangle(4,5);
		Shape s3 = new Triangle(6,7,8);
		
		ArrayList<Shape> shapeList = new ArrayList<>();
		shapeList.add(s1);
		shapeList.add(s2);
		shapeList.add(s3);
		
		for(Shape shape : shapes) {
			System.out.println("Area: " + shape.getArea() + ", Perimeter: " + shape.getPerimeter());
		}
		
	}
}
===========================================
<또 다른 예시>
interface Product {
	public void getPrice();
}

interface Market {
	public void getMarket();
}

class TV implements Product, Market {
	@Override
	public void getPrice() {
		System.out.println("TV 가격 50만원");
	}
	
	@Override
	public void getMarket() {
		System.out.println("슈퍼에서 구입");
	}
}

public class JavaEx01 {

	public static void main(String[] args) {
		Product p1 = new TV();
		p1.getPrice();
		p1.getPrice();

	}

}

4. 람다식

  • 람다식은 익명함수를 간편하게 작성한 함수
  • 람다식은 객체지향 언어에서 클래스 선언없이 메소드를 만들어 사용하는 방법
람다식을 사용한 계산기
interface Calculator {
	int calculate(int a, int b);
}

public class JavaEx04 {

	public static void main(String[] args) {
		Calculator addition = (a,b) -> a+b;
		Calculator subtraction = (a,b) -> a-b;
		Calculator multiplication = (a,b) -> a*b;
		Calculator division = (a,b) -> a/b;
		
		int num1 = 10;
		int num2 = 5;
		
		System.out.println(num1 + "+" + num2 + "=" + addition.calculate(num1, num2));
		System.out.println(num1 + "-" + num2 + "=" + subtraction.calculate(num1, num2));
		System.out.println(num1 + "*" + num2 + "=" + multiplication.calculate(num1, num2));
		System.out.println(num1 + "/" + num2 + "=" + division.calculate(num1, num2));

	}

}
++ 추가내용: 이것이 자바다(교재)
1. 람다식
- 함수형 프로그래밍를 정의하고 데이터 처리부로 보내 데이터를 처리하는 기법.
- 람다식은 다형성의 성격을 가진다.
- 람다식은 인터페이스의 익명 구현 객체이므로 인터페이스 타입의 매개변수에 대입할 수 있다.
- 인터페이스가 함수형 인터페이스임을 보장하기 위해서 @FunctionalInterface 어노테이션을 붙인다.

@FunctionalInterface
public interface Calculable {
	void calculate(int x, int y);
}

public class LambdaExample {
	public static void main(String[] args) {
    	action(x, y) -> {
        	int result = x + y;
            System.out.println("result: " + result);
        });
        
        action(x, y) -> {
        	int result = x - y;
            System.out.println("result: " + result);
        });
      }
      
      public static void action(Calculable calculable) {
      	// 데이터
        int x = 10;
        int y = 4;
        // 데이터 처리
        calculable.calculate(x,y);
       }
}

2. 익명구현 객체(인터페이스 관련)
- 익명객체는 이름이 없는 객체.
- 명시적으로 클래스를 선언하지 않기 때문에 쉽게 객체를 생성
- 익명객체는 필드값, 로컬변수값, 매개변수값으로 주로 사용
- 익명객체는 클래스를 상속하거나 인터페이스를 구현해야만 생성

class Tire {
	public void roll() {
    	System.out.println("일반 타이어가 굴러갑니다");
    }
}

class Car {
	// 필드에 Tire 객체 대입
	private Tire tire1 = new Tire();
    
    // 필드에 익명 자식 객체 대입
    private Tire tire2 = new Tire() {
    	@Override
        public void roll() {
        	System.out.println("익명 자식 Tire 객체1이 굴러갑니다");
        }
     };
     
     // 매소드(필드 이용)
     public void run1() {
     	tire1.roll();
        tire2.roll();
     }
     
     // 메소드(로컬 변수 이용)
     public void run2() {
     	// 로컬 변수에 익명 자식 객체 대입
        Tire tire = new Tire();
        	@Override
            public void roll() {
            	System.out.println("익명 자식 Tire 객체2가 굴러갑니다");
            }
       };
       tire.roll();
  }
  
  // 메소드(매개변수 이용)
  public void run3(Tire tire) {
  	tire.roll();
  }
}

public class CarExample {
	public static void main(String[] args) {
    	// Car객체생성
    	Car car = new Car();
        // 익명 자식 객체가 대입된 필드 사용
        car.run1();
        // 익명 자식 객체가 로컬 변수 사용
        car.run2();
        // 익명 자식 객체가 매개변수 사용
        car.run3(new Tire() {
        	@Override
            public void roll() {
            	System.out.println("익명 자식 Tire 객체 3이 굴러갑니다.");
            }
         });
     }
}     

5. 인터페이스를 이용한 게임 구현

- 아래에 있는 코드를 참고하여 간단한 게임을 구현해볼 것.(복습용)
public interface Pet {
	public void eat();
	public void sleep();
	public void play();
	public void train();
	public void levelUp();
	public boolean endGame();
	public void printInfo();

}

public class Pikachu implements Pet {
	private int experience = 40;
	private int energy = 50;
	private int level = 1;
	@Override
	public void eat() {
		energy += 25; // 먹을때마다 25씩 증가
	}
	@Override
	public void sleep() {
		energy += 10; // 잘때마다 10씩 증가
	}
	@Override
	public void play() {
		// 노는만큼 30씩 감소하고 경험치가 30씩 증가한다.
		energy -= 30;
		experience += 30;
	}
	
	@Override
	public void train() {
		// 훈련하는만큼 에너지 20씩 소모하고 경험치가 20씩 증가함
		energy -= 20;
		experience += 20;
	}
	@Override
	public void levelUp() {
		if(experience > 60) {
			experience -= 40;
			level++;
			System.out.println("레벨업!");
		}
	}
	
	@Override
	public boolean endGame() {
		boolean returnValue = true;
		if(level >= 4) {
			System.out.println("피카츄가 용됨");
			returnValue = false;
		} else if(energy < 0){
			System.out.println("피카츄가 굶어 죽음");
			returnValue = false;
		}
		return returnValue;
	}
	@Override
	public void printInfo() {
		System.out.println("=========================================");
		System.out.println("피카츄 정보입니다.");
		System.out.println("experience: " + experience);
		System.out.println("energy: " + energy);
		System.out.println("level: " + level);
		System.out.println("=========================================");
	}

}

public class Cat implements Pet {
	private int experience = 50;
	private int energy = 60;
	private int level = 1;
	@Override
	public void eat() {
		energy += 25; // 먹을때마다 25씩 증가
	}
	@Override
	public void sleep() {
		energy += 10; // 잘때마다 10씩 증가
	}
	@Override
	public void play() {
		// 노는만큼 30씩 감소하고 경험치가 30씩 증가한다.
		energy -= 30;
		experience += 30;
	}
	
	@Override
	public void train() {
		// 훈련하는만큼 에너지 20씩 소모하고 경험치가 20씩 증가함
		energy -= 20;
		experience += 20;
	}
	@Override
	public void levelUp() {
		if(experience > 60) {
			experience -= 40;
			level++;
			System.out.println("레벨업!");
		}
	}
	
	@Override
	public boolean endGame() {
		boolean returnValue = true;
		if(level >= 4) {
			System.out.println("고양이가 용됨");
			returnValue = false;
		} else if(energy < 0){
			System.out.println("고양이가 굶어 죽음");
			returnValue = false;
		}
		return returnValue;
	}
	@Override
	public void printInfo() {
		System.out.println("=========================================");
		System.out.println("고양이 정보입니다.");
		System.out.println("experience: " + experience);
		System.out.println("energy: " + energy);
		System.out.println("level: " + level);
		System.out.println("=========================================");
	}


}

import java.util.Scanner;

import com.human.character.Pikachu;
import com.human.character.Cat;
import com.human.character.Pet;

public class PlayGame {
	private Pet character = null;
	private boolean flag = true;
	private Scanner scanner = new Scanner(System.in);
	
	public void gameStart() {
		selectCharacter();
		play();
	}
	public void selectCharacter() {
		System.out.println("캐릭터를 선택해주세요.");
		System.out.println("1. 피카츄 | 2. 고양이");
		String ch = scanner.nextLine();
		if(ch.equals("1")) {
			character = new Pikachu();
		} else if(ch.equals("2")) {
			character = new Cat();
		}
	}
	public void play() {
		while(flag) {
			character.printInfo();
			System.out.println("1. 밥먹이기 | 2. 잠재우기 | 3. 놀아주기 | 4. 운동하기 | 5. 종료");
			System.out.print("입력> ");
			String selectNo = scanner.nextLine();
			switch(selectNo) {
				case "1":
					character.eat();
					break;
				case "2":
					character.sleep();
					break;
				case "3":
					character.play();
					break;
				case "4":
					character.train();
					break;
				case "5":
					flag = false;
					break;
				default:
					break;
			}
			character.levelUp();
			if(flag) {
				flag = character.endGame();
			}
		}
	}	
}
import com.human.play.PlayGame;
public class StartGame {

	public static void main(String[] args) {
		PlayGame pg = new PlayGame();
		pg.gameStart();

	}

}
public interface Player {
	public void quest();
	public void play();
	public void train();
	public void rest();
	public void levelUp();
	public boolean endGame();
	public void printInfo();
}

public class Warrior implements Player {
	private int experience = 40;
	private int energy = 50;
	private int level = 50;
	@Override
	public void quest() {
		experience += 30;
	}
	
	@Override
	public void play() {
		energy -= 30;
		experience += 30;
	}
	
	@Override
	public void train() {
		energy -= 20;
		experience += 20;
	}
	
	@Override
	public void rest() {
		energy += 50;
	}
	
	@Override
	public void levelUp() {
		if(experience>100) {
			experience -= 100;
			level++;
			System.out.println("레벨업!");
		}
	}
	
	@Override
	public boolean endGame() {
		boolean returnValue = true;
		if(level >= 60) {
			System.out.println("레벨이 만렙입니다.");
			returnValue = false;
		} else if(energy < 0) {
			returnValue = false;
			System.out.println("게임오버입니다.");
		}
		return returnValue;
	}
	
	public void printInfo() {
		System.out.println("=========================================");
		System.out.println("전사 정보입니다.");
		System.out.println("experience: " + experience);
		System.out.println("energy: " + energy);
		System.out.println("level: " + level);
		System.out.println("=========================================");
	}

}

public class Wizard implements Player {
	private int experience = 40;
	private int energy = 50;
	private int level = 50;
	@Override
	public void quest() {
		experience += 30;
	}
	
	@Override
	public void play() {
		energy -= 30;
		experience += 30;
	}
	
	@Override
	public void train() {
		energy -= 20;
		experience += 20;
	}
	
	@Override
	public void rest() {
		energy += 50;
	}
	
	@Override
	public void levelUp() {
		if(experience>100) {
			experience -= 100;
			level++;
			System.out.println("레벨업!");
		}
	}
	
	@Override
	public boolean endGame() {
		boolean returnValue = true;
		if(level >= 60) {
			System.out.println("레벨이 만렙입니다.");
			returnValue = false;
		} else if(energy < 0) {
			returnValue = false;
			System.out.println("게임오버입니다.");
		}
		return returnValue;
	}
	
	public void printInfo() {
		System.out.println("=========================================");
		System.out.println("마법사 정보입니다.");
		System.out.println("experience: " + experience);
		System.out.println("energy: " + energy);
		System.out.println("level: " + level);
		System.out.println("=========================================");
	}

}

public class Hunter implements Player {
	private int experience = 40;
	private int energy = 50;
	private int level = 50;
	@Override
	public void quest() {
		experience += 30;
	}
	
	@Override
	public void play() {
		energy -= 30;
		experience += 30;
	}
	
	@Override
	public void train() {
		energy -= 20;
		experience += 20;
	}
	
	@Override
	public void rest() {
		energy += 50;
	}
	
	@Override
	public void levelUp() {
		if(experience>100) {
			experience -= 100;
			level++;
			System.out.println("레벨업!");
		}
	}
	
	@Override
	public boolean endGame() {
		boolean returnValue = true;
		if(level >= 60) {
			System.out.println("레벨이 만렙입니다.");
			returnValue = false;
		} else if(energy < 0) {
			returnValue = false;
			System.out.println("게임오버입니다.");
		}
		return returnValue;
	}
	
	public void printInfo() {
		System.out.println("=========================================");
		System.out.println("궁수 정보입니다.");
		System.out.println("experience: " + experience);
		System.out.println("energy: " + energy);
		System.out.println("level: " + level);
		System.out.println("=========================================");
	}

}

import java.util.Scanner;
import com.study.Interface.Player;
import com.study.Interface.Hunter;
import com.study.Interface.Wizard;
import com.study.Interface.Warrior;

public class PlayGame {
	private Player character = null;
	private boolean flag = true;
	private Scanner scanner = new Scanner(System.in);
	
	public void gameStart() {
		selectCharacter();
		play();
	}
	
	public void selectCharacter() {
		System.out.println("캐릭터를 선택해주세요");
		System.out.println("1. 전사 | 2. 마법사 | 3. 궁수");
		String ch = scanner.nextLine();
		if(ch.equals("1")) {
			character = new Warrior();
		} else if(ch.equals("2")) {
			character = new Wizard();
		} else if(ch.equals("3")) {
			character = new Hunter();
		}
	}
	
	public void play() {
		while(flag) {
			character.printInfo();
			System.out.println("1. 의뢰 수행하기 | 2. 던전 돌기 | 3. 훈련하기 | 4. 휴식하기 | 5. 종료");
			System.out.print("선택> ");
			String selectNo = scanner.nextLine();
			switch(selectNo) {
			case "1":
				character.quest();
				break;
			case "2":
				character.play();
				break;
			case "3":
				character.train();
				break;
			case "4":
				character.rest();
				break;
			case "5":
				flag = false;
				break;
			default:
				break;
			}
			character.levelUp();
			if(flag) {
				flag = character.endGame();
			}
		}
	}
}

import com.study.Interface2.PlayGame;

public class StartGame {
	public static void main(String[] args) {
		PlayGame pg = new PlayGame();
		pg.gameStart();
	}
}
profile
IT 개발자가 되기 위한 기록

0개의 댓글