본문 바로가기
자바 (JAVA)

📚 자바 클래스와 객체 연습문제 10개 및 풀이, 실행 결과

by demianpark127 2025. 1. 7.
SMALL

📚 자바 클래스와 객체 연습문제 10개 및 풀이, 실행 결과


📝 문제 1: 은행 계좌 관리 시스템

문제

  • BankAccount 클래스를 만드세요.
  • 필드: accountNumber (String), owner (String), balance (double)
  • 메서드:
    • deposit(double amount) : 입금
    • withdraw(double amount) : 출금 (잔액보다 많이 출금할 수 없음)
    • getBalance() : 잔액 반환

풀이

class BankAccount {
    private String accountNumber;
    private String owner;
    private double balance;

    public BankAccount(String accountNumber, String owner) {
        this.accountNumber = accountNumber;
        this.owner = owner;
        this.balance = 0.0;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        } else {
            System.out.println("Insufficient funds!");
        }
    }

    public double getBalance() {
        return balance;
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("12345", "Alice");
        account.deposit(1000);
        account.withdraw(500);
        System.out.println("Balance: " + account.getBalance());
    }
}
Balance: 500.0

📝 문제 2: 학생 정보 시스템

문제

  • Student 클래스를 만드세요.
  • 필드: name, id, score
  • 메서드: setScore(), getScore(), printInfo()

풀이

class Student {
    private String name;
    private int id;
    private double score;

    public Student(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public void printInfo() {
        System.out.println("Name: " + name + ", ID: " + id + ", Score: " + score);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student = new Student("Bob", 101);
        student.setScore(85.5);
        student.printInfo();
    }
}
Name: Bob, ID: 101, Score: 85.5

📝 문제 3: 자동차 클래스

문제

  • Car 클래스를 만드세요.
  • 필드: model, year, speed
  • 메서드: accelerate(), brake(), getSpeed()

풀이

class Car {
    private String model;
    private int year;
    private double speed;

    public Car(String model, int year) {
        this.model = model;
        this.year = year;
    }

    public void accelerate(double increment) {
        speed += increment;
    }

    public void brake(double decrement) {
        speed = Math.max(speed - decrement, 0);
    }

    public double getSpeed() {
        return speed;
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car("Tesla", 2022);
        car.accelerate(50);
        car.brake(20);
        System.out.println("Speed: " + car.getSpeed());
    }
}
Speed: 30.0

📝 문제 4: 직사각형 면적과 둘레 계산

문제

  • Rectangle 클래스를 만드세요.
  • 필드: width (double), height (double)
  • 메서드:
    • getArea()
    • getPerimeter()

풀이

class Rectangle {
    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);
    }
}

public class Main {
    public static void main(String[] args) {
        Rectangle rect = new Rectangle(5, 7);
        System.out.println("Area: " + rect.getArea());
        System.out.println("Perimeter: " + rect.getPerimeter());
    }
}
Area: 35.0
Perimeter: 24.0

📝 문제 6: 도형 클래스 (다형성 활용)

문제

  • Shape라는 부모 클래스를 만드세요.
  • 메서드: getArea() (추상 메서드)
  • Circle과 Square 클래스를 Shape로부터 상속받아 구현하세요.
    • Circle은 반지름을 받아서 면적을 계산합니다.
    • Square는 변의 길이를 받아서 면적을 계산합니다.

풀이

abstract class Shape {
    abstract double getArea();
}

class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double getArea() {
        return Math.PI * radius * radius;
    }
}

class Square extends Shape {
    private double side;

    public Square(double side) {
        this.side = side;
    }

    @Override
    double getArea() {
        return side * side;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle(5);
        Shape square = new Square(4);

        System.out.println("Circle Area: " + circle.getArea());
        System.out.println("Square Area: " + square.getArea());
    }
}
Circle Area: 78.53981633974483
Square Area: 16.0

📝 문제 7: 간단한 계산기

문제

  • Calculator 클래스를 만드세요.
  • 메서드:
    • add(int a, int b)
    • subtract(int a, int b)
    • multiply(int a, int b)
    • divide(int a, int b) (0으로 나눌 수 없음)
class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }

    public int multiply(int a, int b) {
        return a * b;
    }

    public double divide(int a, int b) {
        if (b == 0) {
            System.out.println("Cannot divide by zero!");
            return 0;
        }
        return (double) a / b;
    }
}

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

        System.out.println("Add: " + calc.add(5, 3));
        System.out.println("Subtract: " + calc.subtract(5, 3));
        System.out.println("Multiply: " + calc.multiply(5, 3));
        System.out.println("Divide: " + calc.divide(5, 0));
    }
}
Add: 8
Subtract: 2
Multiply: 15
Cannot divide by zero!
Divide: 0.0

📝 문제 8: 스마트폰 클래스

문제

  • Smartphone 클래스를 만드세요.
  • 필드: brand, model, batteryLevel
  • 메서드:
    • chargeBattery(int amount) (배터리 최대 100까지 충전)
    • useBattery(int amount) (배터리 소모, 0 미만 방지)
    • showBatteryLevel()

풀이

class Smartphone {
    private String brand;
    private String model;
    private int batteryLevel;

    public Smartphone(String brand, String model) {
        this.brand = brand;
        this.model = model;
        this.batteryLevel = 50; // 초기 배터리 50%
    }

    public void chargeBattery(int amount) {
        batteryLevel = Math.min(batteryLevel + amount, 100);
    }

    public void useBattery(int amount) {
        batteryLevel = Math.max(batteryLevel - amount, 0);
    }

    public void showBatteryLevel() {
        System.out.println(brand + " " + model + " Battery Level: " + batteryLevel + "%");
    }
}

public class Main {
    public static void main(String[] args) {
        Smartphone phone = new Smartphone("Samsung", "Galaxy S23");

        phone.useBattery(30);
        phone.showBatteryLevel();

        phone.chargeBattery(50);
        phone.showBatteryLevel();
    }
}

 

Samsung Galaxy S23 Battery Level: 20%
Samsung Galaxy S23 Battery Level: 70%

📝 문제 9: 책장 관리 시스템

문제

  • Book 클래스를 만드세요.
  • 필드: title, author
  • Bookshelf 클래스를 만들어 책을 추가, 출력할 수 있게 하세요.
  • 메서드:
    • addBook(Book book)
    • displayBooks()

풀이

import java.util.ArrayList;

class Book {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    public void displayInfo() {
        System.out.println("Title: " + title + ", Author: " + author);
    }
}

class Bookshelf {
    private ArrayList<Book> books = new ArrayList<>();

    public void addBook(Book book) {
        books.add(book);
    }

    public void displayBooks() {
        for (Book book : books) {
            book.displayInfo();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Bookshelf shelf = new Bookshelf();
        shelf.addBook(new Book("1984", "George Orwell"));
        shelf.addBook(new Book("Brave New World", "Aldous Huxley"));

        shelf.displayBooks();
    }
}

 

Title: 1984, Author: George Orwell
Title: Brave New World, Author: Aldous Huxley

📝 문제 10: 사용자 로그인 시스템

문제

  • User 클래스를 만드세요.
  • 필드: username, password
  • 메서드:
    • login(String username, String password)
    • logout()

풀이

class User {
    private String username;
    private String password;
    private boolean isLoggedIn = false;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public void login(String username, String password) {
        if (this.username.equals(username) && this.password.equals(password)) {
            isLoggedIn = true;
            System.out.println("Login successful!");
        } else {
            System.out.println("Invalid credentials!");
        }
    }

    public void logout() {
        isLoggedIn = false;
        System.out.println("Logged out!");
    }
}

public class Main {
    public static void main(String[] args) {
        User user = new User("admin", "1234");

        user.login("admin", "1234");
        user.logout();
    }
}

 

Login successful!
Logged out!

 

LIST