1. 시간 관련 클래스
(1) LocalDateTime 클래스
1. 시간 관련 예제
import java.time.LocalDateTime;
public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("현재 날짜와 시간: " + now.toString());
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) {
LocalDateTime startDateTime = LocalDateTime.of(2023, 9,8,11,0,0);
LocalDateTime endDateTime = LocalDateTime.of(2023,9,8,17,30,0);
Period period = Period.between(startDateTime.toLocalDate(), endDateTime.toLocalDate());
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
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;
}
}
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 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;
@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;
rc = new Television();
rc.turnOn();
rc.setVolume(5);
rc.turnOff();
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 {
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 = 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;
}
@Override
public void sleep() {
energy += 10;
}
@Override
public void play() {
energy -= 30;
experience += 30;
}
@Override
public void train() {
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;
}
@Override
public void sleep() {
energy += 10;
}
@Override
public void play() {
energy -= 30;
experience += 30;
}
@Override
public void train() {
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();
}
}