life is egg

22.11.14 [ JAVA기초2] 본문

TIL

22.11.14 [ JAVA기초2]

삶은계란진재혁 2022. 11. 15. 00:25

error: class Human is public, should be declared in a file named Human.java

오늘의 오류...

 

자바는. 클래스명도 신중하게 지어줘야함..!

main(String[] args)가 들어가는 클래스...의 클래스이름과 생성하는 클래스파일명 이름을 맞춰줘야해..!

 

 

새로운 패키지 생성해서 숙제하는데 또또 한글 인식못해서 강제로 영어쓰는중

영어가 원어민인 사람들이 부럽기 시작

되다 안되다 한다 사람 짜증남 ~

 

숙제 조건

더보기

객체지향에서 배운 개념과 문법을 이용해서 다음 요구조건을 만족하는 클래스를 작성하시요. 여러분이 게임을 만든다고 생각해보세요.

요구사항

  1. 사람은 자식, 부모님, 조부모님이 있다.
  2. 모든 사람은 이름, 나이, 현재 장소정보(x,y좌표)가 있다.
  3. 모든 사람은 걸을 수 있다. 장소(x, y좌표)로 이동한다.
  4. 자식과 부모님은 뛸 수 있다. 장소(x, y좌표)로 이동한다.
  5. 조부모님의 기본속도는 1이다. 부모의 기본속도는 3, 자식의 기본속도는 5이다.
  6. 뛸때는 속도가 기본속도대비 +2 빠르다.
  7. 수영할때는 속도가 기본속도대비 +1 빠르다.
  8. 자식만 수영을 할 수 있다. 장소(x, y좌표)로 이동한다.

위 요구사항을 만족하는 클래스들을 바탕으로, Main 함수를 다음 동작을 출력(System.out.println)하며 실행하도록 작성하시오. 이동하는 동작은 각자 순서가 맞아야 합니다.

  1. 모든 종류의 사람의 인스턴스는 1개씩 생성한다.
  2. 모든 사람의 처음 위치는 x,y 좌표가 (0,0)이다.
  3. 모든 사람의 이름, 나이, 속도, 현재위치를 확인한다.
  4. 걸을 수 있는 모든 사람이 (1, 1) 위치로 걷는다.
  5. 뛸 수 있는 모든 사람은 (2,2) 위치로 뛰어간다.
  6. 수영할 수 있는 모든 사람은 (3, -1)위치로 수영해서 간다.

자바 숙제 -1   아직도 접근수준 지시자는 햇갈린다.. 걍 다 퍼블릭걸고싶다

값의 증감을 계속 저장하고 싶을때는 = 말고 +=를 이용하자..!

더보기

 

package homework;

class human {
    int x, y ;
    int z ;
    void move(int x, int y) {
        this.x +=x;
        this.y +=y;
        this.z =z;
    }
    public void location(){
        System.out.println("current location is  : " + "("+this.x+" , "+this.y+")" + "speed is : "+ this.z);
    }
}

class Son extends  human{
    int age;
    String name;
    public Son(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    void move(int x,int y){
        System.out.println("--------------------------------------------------------");
        this.z = 5;
        location();
        System.out.println(name + "("+age+"age)"+"is moving");
        this.x += 5*x;
        this.y += 5*y;
        location();
        System.out.println("--------------------------------------------------------");
    }
    void swim(int x,int y){
        System.out.println("--------------------------------------------------------");
        this.z = 6;
        location();
        System.out.println(name + "("+age+"age)"+" is swimming.");
        this.x += 6*x;
        this.y += 6*y;
        location();
        System.out.println("--------------------------------------------------------");

    }
    void run(int x,int y){
        System.out.println("--------------------------------------------------------");
        this.z = 7;
        location();
        System.out.println(name + "("+age+"age)"+" is running");
        this.x +=7*x;
        this.y +=7*y;
        location();
        System.out.println("--------------------------------------------------------");
    }
}

class Parent extends human {
    int age;
    String name;

    public Parent(String name, int age) {

        this.name = name;
        this.age = age;
    }

    void run(int x, int y) {
        System.out.println("--------------------------------------------------------");
        this.z = 5;
        location();
        System.out.println(name + "("+age+"age)"+" is running.");
        this.x += 5 * x;
        this.y += 5 * y;
        location();
        System.out.println("--------------------------------------------------------");
    }
    @Override
    void move(int x,int y){
        System.out.println("--------------------------------------------------------");
        this.z = 3;
        location();
        System.out.println(name + "("+age+"age)"+" is moving.");
        this.x += 3*x;
        this.y += 3*y;
        location();
        System.out.println("--------------------------------------------------------");
    }
}
class SuperParent extends human{
    int age;
    String name;
    public  SuperParent(String name, int age){
        this.name = name;
        this.age = age;
    }
    @Override
    void move(int x,int y){
        System.out.println("--------------------------------------------------------");
        this.z = 1;
        location();
        System.out.println(name + "("+age+"age)"+" is moving.");
        this.x += x;
        this.y += y;
        location();
        System.out.println("--------------------------------------------------------");
    }

}

public class Movemove {
    public  static void  main(String[] args){
        Son wogur = new Son("jin", 20);
        Parent wwogur = new Parent("parent JJin", 40);
        SuperParent wwwogur = new SuperParent("super_parent JJJin", 60);

        wogur.move(1,1);
        wwogur.move(1,1);
        wwwogur.move(1,1);

        wogur.run(2,2);
        wwogur.run(2,2);

        wogur.swim(3,-1);
    }
}

강사님 풀이 ... 인텔리제이를 적극 이용하자..+인터페이스를 잘이용하신다  페이지를 잘 나누신다 ..!

더보기

Human.java

public class Human {
    String name;
    int age;
    int speed;
    int x, y;

    public Human(String name, int age, int speed, int x, int y) {
        this.name = name;
        this.age = age;
        this.speed = speed;
        this.x = x;
        this.y = y;
    }

    public Human(String name, int age, int speed) {
        this(name, age, speed, 0, 0);
    }

    public String getLocation() {
        return "(" + x + ", " + y + ")";
    }
    protected void printWhoAmI() {
        System.out.println("My name is " + name + ". " + age + " aged.");
    }
}

Walkable.java

 public interface Walkable { void walk(int x, int y); }

Runnable.java

public interface Runnable {
    void run(int x, int y);
}

Swimmable.java

public interface Swimmable {
    void swim(int x, int y);
}

GrandParent.java

public class GrandParent extends Human implements Walkable {
    public GrandParent(String name, int age) {
        super(name, age, 1);
    }

    @Override
    public void walk(int x, int y) {
        printWhoAmI();
        System.out.println("walk speed: " + speed);
        this.x = x;
        this.y = y;
        System.out.println("Walked to " + getLocation());
    }
}

Parent.java

public class Parent extends Human implements Walkable, Runnable{
    public Parent(String name, int age) {
        super(name, age, 3);
    }

    @Override
    public void run(int x, int y) {
        printWhoAmI();
        System.out.println("run speed: " + (speed + 2));
        this.x = x;
        this.y = y;
        System.out.println("Ran to " + getLocation());
    }

    @Override
    public void walk(int x, int y) {
        printWhoAmI();
        System.out.println("walk speed: " + speed);
        this.x = x;
        this.y = y;
        System.out.println("Walked to " + getLocation());
    }
}

Child.java

public class Child extends Human implements Walkable, Runnable, Swimmable{
    public Child(String name, int age) {
        super(name, age, 5);
    }

    @Override
    public void swim(int x, int y) {
        printWhoAmI();
        System.out.println("swimming speed: " + (speed + 1));
        this.x = x;
        this.y = y;
        System.out.println("Swum to " + getLocation());
    }

    @Override
    public void run(int x, int y) {
        printWhoAmI();
        System.out.println("run speed: " + (speed + +2));
        this.x = x;
        this.y = y;
        System.out.println("Ran to " + getLocation());
    }

    @Override
    public void walk(int x, int y) {
        printWhoAmI();
        System.out.println("walk speed: " + speed);
        this.x = x;
        this.y = y;
        System.out.println("Walked to " + getLocation());
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Human grandParent = new GrandParent("할아버지", 70);
        Human parent = new Parent("엄마", 50);
        Human child = new Child("나", 20);

        Human[] humans = { grandParent, parent, child };
        for (Human human : humans) {
            System.out.println(human.name + ", 나이: " + human.age + ", 속도: " + human.speed + ", 장소: " + human
                    .getLocation());
        }
        System.out.println("<활동 시작>");
        for (Human human : humans) {
            if (human instanceof Walkable) {
                ((Walkable) human).walk(1, 1);
                System.out.println(" - - - - - - ");
            }
            if (human instanceof Runnable) {
                ((Runnable) human).run(2, 2);
                System.out.println(" - - - - - - ");
            }
            if (human instanceof Swimmable) {
                ((Swimmable) human).swim(3, -1);
                System.out.println(" - - - - - - ");
            }
        }
    }
}

 

instenceof...?

JAVA 오늘의 기본 문법 강의 끝~ 

더보기

예외처리

프로그램의 비정상 종료를 막기 위해

문제가 발생한걸 인지하기 위해

> 상속을 이용해 모든 예외를 담당...

 

예외의 종류 

1.에러

>내가 어떻게 할수 없는것..들

2.예외

>내가 처리해줘야 하는것들

 

방법

try -catch(좁은범위)-catch(넓은범위)-......-(finally-항상실행됨)

try-with-resource   /// 이해가 안됨

 

메소드에서의 예외선언

catch문을 이용해서 예외처리를 하지 않은 경우, 메소드에 throws로 예외가 발생할 수 있다는 것을 알려주어야 합니다. throws 키워드가 있는 함수를 호출한다면, caller 쪽에서 catch와 관련된 코드를 작성해주어야 합니다.

void method() throws IndexOutOfBoundsException, IllegalArgumentException {
    //메소드의 내용
}

숙제2 조건

더보기

다음 스니펫에 있는 divide() 함수는 매개변수(parameter)에 들어오는 값에 따라서 ArithmeticException과 ArrayIndexOutOfBoundsException이 발생할 수 있습니다.

  1. throws 키워드를 통해서 divide() 함수에서 발생할 수 있는 exception의 종류가 무엇인지 알게 해주세요.
  2. Main 함수에서 try-catch 문을 이용해서, 다음 동작을 구현하세요.
    1. ArithmeticException이 발생할 때는 잘못된 계산임을 알리는 문구를 출력하세요.
    2. ArrayIndexOutOfBoundsException이 발생할 때는 현재 배열의 index범위를 알려주는 문구를 출력하세요.

숙제 2 내풀이 

더보기
class ArrayCalculation {

    int[] arr = { 0, 1, 2, 3, 4 };

    public int divide(int denominatorIndex, int numeratorIndex) throws ArithmeticException,ArrayIndexOutOfBoundsException {
        return arr[denominatorIndex] / arr[numeratorIndex];
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayCalculation arrayCalculation = new ArrayCalculation();

        try {
            System.out.println("2 / 1 = " + arrayCalculation.divide(2, 1));
           // System.out.println("1 / 0 = " + arrayCalculation.divide(1, 0)); // java.lang.ArithmeticException: "/ by zero"
            System.out.println("Try to divide using out of index element = "
                    + arrayCalculation.divide(5, 0)); // java.lang.ArrayIndexOutOfBoundsException: 5
        } catch (ArithmeticException e) {
            System.out.println("0은 분자로 올 수 없습니다.");
        } catch (ArrayIndexOutOfBoundsException e){
            System.out.println("배열의 길이는 4이하로 입력해야합니다.");
        }

    }
}

강사님 풀이 아 ... 하나하나 써주는거구나... 완전 눈가리고 아웅 아닌갑

  내가 배워 갈거는 ... 다른 클래스에 있는 배열 호출시 클래스명.배열명

더보기
class ArrayCalculation {

    int[] arr = { 0, 1, 2, 3, 4 };

    public int divide(int denominatorIndex, int numeratorIndex)
            throws ArithmeticException, ArrayIndexOutOfBoundsException {
        return arr[denominatorIndex] / arr[numeratorIndex];
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayCalculation arrayCalculation = new ArrayCalculation();

				System.out.println("2 / 1 = " + arrayCalculation.divide(2, 1));
        try {
            System.out.println(
                    "1 / 0 = " + arrayCalculation.divide(1, 0));
        } catch (ArithmeticException arithmeticException) {
            System.out.println("잘못된 계산입니다. " + arithmeticException.getMessage());
        }
        try {
            System.out.println("Try to divide using out of index element = "
                               + arrayCalculation.divide(5, 0)); 
        } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) {
            System.out.println(
                    "잘못된 index 범위로 나누었습니다. 타당 index 범위는 0부터" + (arrayCalculation.arr.length - 1) + "까지 입니다.");
        }
    }

}

 

퀴즈3

나의 어거지 풀이

더보기
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter homework = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        DateTimeFormatter homework_2 = DateTimeFormatter.ofPattern("kk");
        DateTimeFormatter homework_3 = DateTimeFormatter.ofPattern("E");
        String a = homework.format(LocalDate.now());
        String b = homework_2.format(LocalTime.now());
        String c = homework_3.format(LocalDate.now());
        System.out.println(a+"  "+b+"/"+c);


    }
}

 

강사님 풀이 ?.... 음.... 시간/분 이넹.... 머야 ?!   .ㅠ_ㅠ  시간은 h도 되지만 kk도 된다 E는 요일

 

 

'TIL' 카테고리의 다른 글

22.11.16 [프로그래머스 Lv0]  (0) 2022.11.17
22.11.15 [Java 활용편]  (0) 2022.11.15
22.11.11 [CS_CPU & 알고리즘]  (0) 2022.11.11
22.11.10 [자료구조.. & python]  (0) 2022.11.10
22.11.09 [파이썬기본문법 2 & 알고리즘]  (0) 2022.11.10
Comments