실습 문제 1: 카드 게임 시뮬레이터
import java.util.Random;
public class Main {
public static void main(String[] args) {
Player[] players = new Player[2];
Random random = new Random();
for (int i = 0; i < players.length; i++) {
players[i] = new Player(Integer.toString(random.nextInt(1000)), i);
}
Deck deck = new Deck();
Game game = new Game(players, deck);
game.start();
}
}
public class Card {
private int number;
private Suit suit;
public Card(int number, int suit) {
this.number = number;
switch (suit) {
case 0:
this.suit = Suit.Hearts;
break;
case 1:
this.suit = Suit.Diamonds;
break;
case 2:
this.suit = Suit.Clubs;
break;
case 3:
this.suit = Suit.Spades;
break;
default:
throw new Error("Invalid suit number!");
}
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Suit getSuit() {
return suit;
}
public void setSuit(Suit suit) {
this.suit = suit;
}
}
import java.util.Random;
public class Deck {
public Card[] cards;
public Deck(Card[] cards) {
this.cards = cards;
}
public Deck() {
Card[] cards = new Card[52];
for (int i = 0; i < cards.length; i++) {
cards[i] =
new Card(
(int) (Math.random() * 13 + 1),
(int) (Math.random() * 3 + 1));
}
this.cards = cards;
}
public void shuffle() {
Random random = new Random();
for (int i = cards.length - 1; i > 0; i--) {
int targetIndex = random.nextInt(i);
Card temp = cards[targetIndex];
cards[targetIndex] = cards[i];
cards[i] = temp;
}
}
public Card draw() {
for (int i = cards.length - 1; i >= 0; i--) {
if (cards[i] != null) {
Card drawingCard = cards[i];
cards[i] = null;
return drawingCard;
}
}
// Fallback but it shouldn't reach here within 5 draws.
return cards[cards.length - 1];
}
}
public class Game {
private Player[] players;
private Deck deck;
public Game(Player[] players, Deck deck) {
this.players = players;
this.deck = deck;
}
void start() {
deck.shuffle();
for (int i = 0; i < 5; i++) {
int player0Number = deck.draw().getNumber();
int player1Number = deck.draw().getNumber();
if (player0Number > player1Number) {
System.out.println("Player 0 gets a point!");
players[0].addScore(1);
} else {
System.out.println("Player 1 gets a point!");
players[1].addScore(1);
}
}
if (players[0].getScore() > players[1].getScore()) {
System.out.println("Player 0 won!");
} else {
System.out.println("Player 1 won!");
}
}
}
public class Player {
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public void addScore(int points) {
this.score += points;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
public enum Suit {
Hearts, Diamonds, Clubs, Spades
}
실습 문제 2: 간단한 주사위 게임
public class Main {
public static void main(String[] args) {
Player[] players = {
new Player("Steve"),
new Player("Tim"),
new Player("Bill")
};
DiceGame game = new DiceGame(players);
game.play();
}
}
public class Dice {
private int sides = 6;
public Dice(int sides) {
this.sides = sides;
}
int roll() {
System.out.println((int) Math.random() * sides + 1);
return (int) (Math.random() * sides) + 1;
}
}
public class DiceGame {
private Player[] players;
private Dice dice;
public DiceGame(Player[] players) {
if (players.length < 2 || players.length > 4) {
throw new Error("Number of players much be more than 0 and less than 5!");
}
this.players = players;
this.dice = new Dice(6);
}
public DiceGame(Player[] players, Dice dice) {
if (players.length < 2 || players.length > 4) {
throw new Error("Number of players much be more than 0 and less than 5!");
}
this.players = players;
this.dice = dice;
}
void play() {
int round = 1;
while (true) {
System.out.println("Round " + round + ":");
for (Player player : players) {
int rolledNumber = dice.roll();
player.addScore(rolledNumber);
System.out.println(player.getName() + " rolls " + rolledNumber);
}
System.out.println();
boolean isOver = getWinner();
if (isOver && round >= 3) {
break;
}
round++;
}
}
boolean getWinner() {
Player highestPlayer = players[0];
for (int i = 1; i < players.length; i++) {
if (highestPlayer.getScore() == players[i].getScore()) {
return false;
}
if (highestPlayer.getScore() > players[i].getScore()) {
highestPlayer = players[i];
}
}
System.out.println("Winner:");
System.out.println(highestPlayer.getName());
return true;
}
}
public class Player {
private String name;
private int score;
public Player(String name) {
this.name = name;
}
void addScore(int points) {
this.score += points;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
실습 문제 3
public class Account {
private String accountHolderName;
private double balance;
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
public void checkBalance() {
System.out.println("My balance: " + balance);
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
}
import java.io.IOException;
import java.util.HashMap;
public class Main {
public static void main(String[] args) throws IOException {
HashMap<String, Account> accounts = new HashMap<>();
accounts.put("Steve", new Account());
accounts.put("Tim", new Account());
ATM atm = new ATM(accounts);
while (true) {
atm.performTransaction();
}
}
}
import java.util.HashMap;
import java.util.Scanner;
public class ATM {
private HashMap<String, Account> accounts;
private Scanner scanner;
public ATM(HashMap<String, Account> accounts) {
this.accounts = accounts;
this.scanner = new Scanner(System.in);
}
public void performTransaction() {
while (true) {
System.out.println("Enter Your name:");
String name = scanner.nextLine();
Account usingAccount = accounts.get(name);
if (usingAccount != null) {
runATMSession(usingAccount);
break;
} else {
System.out.println("Account not found. Please try again.");
}
}
}
private int getValidOption(int min, int max) {
// Makes sure the user selects a valid option within the range.
while (true) {
try {
int choice = Integer.parseInt(scanner.nextLine().trim());
if (choice >= min && choice <= max) {
return choice;
} else {
System.out.println("Invalid choice! Please select a number between "
+ min + " and " + max + ".");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
}
}
}
private void runATMSession(Account usingAccount) {
while (true) {
System.out.println();
System.out.println("Welcome to the ATM!");
System.out.println("1. Check Balance");
System.out.println("2. Deposit Money");
System.out.println("3. Withdraw Money");
System.out.println("4. Exit");
System.out.println("Choose an option");
int option = getValidOption(1, 4);
switch (option) {
case 1:
usingAccount.checkBalance();
break;
case 2:
usingAccount.deposit(getAmount());
break;
case 3:
usingAccount.withdraw(getAmount());
break;
case 4:
System.out.println("Thank you for using the ATM!");
return; // Exit the session
default:
System.out.println("Invalid option. Please try again.");
}
}
}
private double getAmount() {
while (true) {
System.out.println("Type amount:");
try {
double value = Double.parseDouble(scanner.nextLine().trim());
return value;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
}
}
}
}
실습 문제 4: 학생 성적 관리 프로그램