풀스택 개발자 과정 47일차

너구·2026년 7월 14일

풀스택 성장과정

목록 보기
50/79

GetSetTest

package Day10;

class A {
    private int a;
    private int b;
    private String str;

    public A(int a, int b, String str) {
        this.a = a;
        this.b = b;
        this.str = str;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }
}


public class GetSetTest {
    static void main() {

    }
}

MapTest1

package Day10;

import java.util.*;

public class MapTest1 {
    static void main() {
        Scanner p = new Scanner(System.in);
        System.out.print("가위, 바위, 보 게임 선택(1.가위 2.바위, 3,보): ");
        int user = p.nextInt()-1; // 1. 가위-1 = 0 2. 바위-1 = 1 3.보-1 = 2

        Random r = new Random();
        int com = r.nextInt(3); // 0 1 2
        //        키        값
        HashMap<Integer, String> hm = new HashMap<Integer, String>();

        // put 추가 -> (키, 값);
        hm.put(0, "가위"); // map에 추가
        hm.put(1, "바위");
        hm.put(2, "보");

        /*
        안된다. 아래처럼 하려면 List
        for(int i = 0; i < hm, size(); i++) {
            hm.get(i)
            }
         */
        Set<Integer> key=hm.keySet();

        // set -> Iterator
        Iterator<Integer> i = key.iterator();

        while(i.hasNext()) {
            Integer temp = i.next();
            System.out.println(hm.get(temp));
        }

        String value1 = hm.get(user);
        System.out.println("당신은 " + value1 + "를 냈습니다.");
        String value2 = hm.get(com);
        System.out.println("컴퓨터는 " + value2 + "를 냈습니다.");
        System.out.println("====================================");
        System.out.print("게임 결과: ");

        if (user == com) {
            System.out.println("비겼습니다.");
            // 1 -> 가위 1-1 = 0 ==       2 -> 보 2+1 = 3 % 3 = 0
            // 2 -> 바위 2-1 = 1 ==       0 -> 가위 0+1 = 1 % 3 = 1
        } else if (user == (com+1) % 3) {
            System.out.println("당신이 이겼습니다.");
        } else {
            System.out.println("컴퓨터가 이겼습니다.");
        }

    }
}

MapTest2

package Day10;

import java.util.HashMap;

class C {
    int k;
}

class D {
    String str;
}

public class MapTest2 {
    static void main() {
        //     키 C 값 D
        HashMap<C, D> map = new HashMap<C, D>();
        // C 객체 생성
        C c = new C();
        // C 객체 생성
        C c1 = new C();

        map.put(c, new D());
        map.get(c1); // null
        map.get(c); // 객체 D를 리턴
    }
}

Q1

package Day10;

/*
동물 프로그램을 만든다.

Animal이라는 부모 추상 클래스를 만들고,
동물들이 공통으로 가지는 이름과 색상을 관리한다.
색상은 랜덤으로 정하고, talk() 메서드는 추상 메서드로 만든다.

Dog, Cat, Bird 클래스를 만들어 Animal을 상속받는다.
각 동물은 자신의 종류를 랜덤으로 정하고,
talk() 메서드를 오버라이딩해서 각자 다른 행동을 출력한다.

main에서는 Animal 타입의 List를 만들고
강아지 3마리, 고양이 2마리, 새 1마리를 추가한다.
이후 List의 순서를 랜덤으로 섞고,
반복문을 통해 모든 동물의 talk() 메서드를 실행한다.
*/

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

abstract class Animal {
    private String name;
    private String color;

    Animal() {
        Random r = new Random();
        String[] colors = {"갈색", "검은색", "흰색", "노란색", "점박이"};
        color = colors[r.nextInt(colors.length)];
    }

    public abstract void talk();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

class Dog extends Animal {
    Dog() {
        Random r = new Random();
        String[] dogs = {"말티즈", "요크셔테리어", "포메라니안", "시바", "웰시코기"};
        setName(dogs[r.nextInt(dogs.length)]);
    }

    @Override
    public void talk() {
        System.out.println(getColor() + "의 " + getName() + "는 짖는다");
    }
}

class Cat extends Animal {
    Cat() {
        Random r = new Random();
        String[] cats = {"먼치킨", "스핑크스", "뱅갈", "샴", "폴드"};
        setName(cats[r.nextInt(cats.length)]);
    }
    @Override
    public void talk() {
        System.out.println(getColor() + "의 " + getName() + "는 야옹한다");
    }
}

class Bird extends Animal {
    Bird() {
        Random r = new Random();
        String[] birds = {"앵무새", "참새", "닭", "까마귀", "비둘기"};
        setName(birds[r.nextInt(birds.length)]);
    }
    @Override
    public void talk() {
        System.out.println(getColor() + "의 " + getName() + "는 날아다닌다");
    }
}

public class Q1 {
    static void main() {
        List<Animal> animals = new ArrayList<>();

        animals.add(new Dog());
        animals.add(new Dog());
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Cat());
        animals.add(new Bird());

        Collections.shuffle(animals);

        for (int i = 0; i < animals.size(); i++) {
            animals.get(i).talk();
        }
    }
}

Q1_1 선생님 풀이

package Day10;

import java.util.Random;

class Animal1 {
    private  String name;
    private  String color;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Dog1 extends Animal1 {

    Dog1 () {
        Random r = new Random();
        String[] types = {"말티즈" , "요크셔테리어 ", "포메라니안", "시바", "웰시코기"};
        String [] colors = {"갈색", "검은색", "흰색", "노란색", "점박이"};

        setName(types[r.nextInt(types.length)] );
        setColor(colors[r.nextInt(types.length)] );
    }

    void  bow () {
        System.out.println(getColor() + "의" + getName() + "는 짖는다");
    }
}

class Cat1 extends Animal1 {

    Cat1 () {
        Random r = new Random();
        String[] types = {"먼치킨" , "스핑크스", "뱅갈", "샴", "폴드"};
        String [] colors = {"갈색", "검은색", "흰색", "노란색", "점박이"};

        setName(types[r.nextInt(types.length)] );
        setColor(colors[r.nextInt(types.length)] );
    }

    void yayong () {
        System.out.println(getColor() + "의" + getName() + "는 야옹한다");
    }
}

class Bird1 extends Animal1 {
    Bird1 () {
        Random r = new Random();
        String[] types = {"앵무새" , "참새", "닭", "까마귀", "비둘기"};
        String [] colors = {"갈색", "검은색", "흰색", "노란색", "점박이"};

        setName(types[r.nextInt(types.length)] );
        setColor(colors[r.nextInt(types.length)] );
    }

    void fly () {
        System.out.println(getColor() + "의" + getName() + "는 날아다닌다");
    }
}
public class Q1_1 {
    static void main() {

        Dog1 d1 = new Dog1();
        Dog1 d2 = new Dog1();
        Dog1 d3 = new Dog1();

        Cat1 c1 = new Cat1();
        Cat1 c2 = new Cat1();

        Bird1 b1 = new Bird1();

        d1.bow();
        d2.bow();
        d3.bow();

        c1.yayong();
        c2.yayong();

        b1.fly();
    }
}

java와 DB 연결

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>effect</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>25</maven.compiler.source>
        <maven.compiler.target>25</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.10.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>9.4.0</version>
        </dependency>
    </dependencies>

</project>

maven으로 생성
xml 파일에 gson 의존성 주입

Main

package JSONTest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
import java.sql.ResultSet;

public class Main {
    static void main() {
        while (true) {

            Scanner sc = new Scanner(System.in);
            System.out.println("1.입력 2.검색 3.전체출력 4.삭제 5.종료");
            System.out.print("번호를 입력하세요: ");
            int num = sc.nextInt();

            // 추가
            if (num == 1) {
                System.out.print("이름: ");
                String name = sc.next();

                System.out.print("전화번호: ");
                String tel = sc.next();

                System.out.print("나이: ");
                int age = sc.nextInt();

                String url = "jdbc:mysql://localhost:3306/addressbook_db";
                String user = "root";
                String password = "1234";

                try {
                    Connection conn =
                            DriverManager.getConnection(url, user, password);

                    String sql = "INSERT INTO person(name, tel, age) VALUES(?,?,?)";

                    PreparedStatement pstmt =
                            conn.prepareStatement(sql);

                    pstmt.setString(1, name);
                    pstmt.setString(2, tel);
                    pstmt.setInt(3, age);

                    pstmt.executeUpdate();

                    System.out.println("저장 완료!");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 검색
            } else if (num == 2) {
                System.out.print("이름: ");
                String name = sc.next();

                String url = "jdbc:mysql://localhost:3306/addressbook_db";
                String user = "root";
                String password = "1234";

                try {
                    Connection conn =
                            DriverManager.getConnection(url, user, password);

                    String sql = "SELECT * FROM person WHERE name = ?";

                    PreparedStatement pstmt =
                            conn.prepareStatement(sql);

                    pstmt.setString(1, name);

                    ResultSet rs = pstmt.executeQuery();

                    if (rs.next()) {
                        System.out.println("이름: " + rs.getString("name"));
                        System.out.println("전화번호: " + rs.getString("tel"));
                        System.out.println("나이: " + rs.getInt("age"));
                    } else {
                        System.out.println("찾는 사람이 없습니다.");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 전체출력
            } else if (num == 3) {
                String url = "jdbc:mysql://localhost:3306/addressbook_db";
                String user = "root";
                String password = "1234";

                try {
                    Connection conn =
                            DriverManager.getConnection(url, user, password);

                    String sql = "SELECT * FROM person";

                    PreparedStatement pstmt =
                            conn.prepareStatement(sql);

                    ResultSet rs = pstmt.executeQuery();

                    while (rs.next()) {
                        System.out.println("이름: " + rs.getString("name"));
                        System.out.println("전화번호: " + rs.getString("tel"));
                        System.out.println("나이: " + rs.getInt("age"));
                        System.out.println("----------------");
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }
                // 삭제
            } else if (num == 4) {
                System.out.print("이름 입력: ");
                String name = sc.next();

                String url = "jdbc:mysql://localhost:3306/addressbook_db";
                String user = "root";
                String password = "1234";

                try {
                    Connection conn =
                            DriverManager.getConnection(url, user, password);

                    String sql = "DELETE FROM person WHERE name = ?";

                    PreparedStatement pstmt =
                            conn.prepareStatement(sql);

                    pstmt.setString(1, name);

                    int result = pstmt.executeUpdate();

                    if (result > 0) {
                        System.out.println("삭제 완료!");
                    } else {
                        System.out.println("저장된 이름이 없습니다.");
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                }
                // 프로그램 종료
            } else if (num == 5) {
                System.out.println("시스템을 종료합니다.");
                break;
            } else {
                System.out.println("잘못된 입력입니다.");
            }
        }
    }
}

마무리

전화번호부가 완성되었다.

main문안에 모든 걸 다 적었다.
사실 분리도 하고 그랬어야했는데 아직은 try문 안에 sql 연동해서 불러오고 작업하는 것도 어려워서 ai의 도움을 많이 받았다.
이런 작업을 많이 해서 숙련도를 높여야 될 거 같다라는 생각이 들었다.
그래도 db 연결해서 어케저케 돌아가는 프로그램을 보니 재밌기도 하고 뿌듯하기도 했다.

0개의 댓글