4.2 자바 클래스 만들기
[예제 4-1] Circle 클래스의 긱체 생성 및 활용
package p187_Circle;
public class p187_Circle {
int radius;
String name;
public p187_Circle() {}
public double getArea() {
return 3.14 * radius * radius;
}
public static void main(String[] args) {
p187_Circle pizza;
pizza = new p187_Circle();
pizza.radius = 10;
pizza.name = "자바피자";
double area = pizza.getArea();
System.out.println(pizza.name + "의 면적은 " + area);
p187_Circle donut = new p187_Circle();
donut.radius = 2;
area = donut.getArea();
System.out.println(donut.name + "의 면적은 "+area);
}
}

[예제 4-2] Rectangle 클래스 만들기 연습
package p189_RectApp;
import java.util.Scanner;
class Rectangle{
int width;
int height;
public int getArea() {
return width*height;
}
}
public class p189_RectApp {
public static void main(String[] args) {
Rectangle rect = new Rectangle();
Scanner scanner = new Scanner(System.in);
System.out.print(">> ");
rect.width = scanner.nextInt();
rect.height = scanner.nextInt();
System.out.println("사각형의 면적은 " + rect.getArea());
scanner.close();
}
}

4.3 생성자
[예제 4-3] 두 개의 생성자를 가진 Circle 클래스
package p191_Circle;
public class p191_Circle {
int radius;
String name;
public p191_Circle() {
radius = 1; name = "";
}
public p191_Circle(int r, String n) {
radius = r; name = n;
}
public double getArea() {
return 3.14 * radius * radius;
}
public static void main(String[] args) {
p191_Circle pizza = new p191_Circle(10, "자바피자");
double area = pizza.getArea();
System.out.println(pizza.name + "의 면적은 " + area);
p191_Circle donut = new p191_Circle();
donut.name = "도넛 피자";
area = donut.getArea();
System.out.println(donut.name + "의 면적은 " + area);
}
}

[예제 4-4] 생성자 선언 및 활용 연습
package p193_Book;
public class p193_Book {
String title;
String author;
public p193_Book(String t) {
title = t;
author = "작자미상";
}
public p193_Book(String t, String a) {
title = t;
author = a;
}
public static void main(String[] args) {
p193_Book littlePrince = new p193_Book("어린왕자", "생택쥐페리");
p193_Book loveStory = new p193_Book("춘향전");
System.out.println(littlePrince.title + " " + littlePrince.author);
System.out.println(loveStory.title + " " + loveStory.author);
}
}

[예제 4-5] this()로 다른 생성자 호출
package p199_Book;
public class p199_Book {
String title;
String author;
void show() { System.out.println(title + " " + author); }
public p199_Book(){
this("", "");
System.out.println("생성자 호출됨");
}
public p199_Book(String title) {
this(title, "작자미상");
}
public p199_Book(String title, String author) {
this.title = title;
this.author = author;
}
public static void main(String[] args) {
p199_Book littlePrince = new p199_Book("어린왕자", "생택쥐페리");
p199_Book loveStory = new p199_Book("춘향전");
p199_Book emptyBook = new p199_Book();
loveStory.show();
}
}

4.4 객체 배열
[예제 4-6] Circle 객체 배열 만들기
package p206_CircleArray;
import p206_CircleArray.Circle;
class Circle{
int radius; //멤버 변수
public Circle(int radius) {
this.radius = radius; //this.radius는 맴버변수, radius는 매개변수
}
public double getArea() {
return 3.14 * radius * radius;
}
}
public class p206_CircleArray {
public static void main(String[] args) {
Circle [] c;
c = new Circle[5];
for(int i = 0; i<c.length; i++)
c[i] = new Circle(i);
for(int i = 0; i<c.length; i++)
System.out.print((int)(c[i].getArea()) + " ");
}
}

[예제 4-7] 객체 배열 만들기 연습
package p207_BookArray;
import java.util.Scanner;
class Book{
String title, author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}
public class p207_BookArray {
public static void main(String[] args) {
Book [] book = new Book[2];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i<book.length; i++) {
System.out.print("제목 >> ");
String title = scanner.nextLine();
System.out.print("저자 >> ");
String author = scanner.nextLine();
book[i] = new Book(title, author);
}
for(int i = 0; i<book.length; i++)
System.out.print("(" + book[i].title + ", " + book[i].author + ")");
scanner.close();
}
}

4.5 메소드 활용
[예제 4-8 인자로 배열이 전달되는 예]
package p212_ArrayPassingEx;
public class p212_ArrayPassingEx {
static void replaceSpace(char a[]) {
for(int i = 0; i<a.length; i++)
if(a[i] == ' ') a[i] = ',';
}
static void printCharArray(char a[]) {
for(int i = 0; i<a.length; i++)
System.out.print(a[i]);
System.out.println();
}
public static void main(String args[]) {
char c[] = {'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'p','e','n','c', 'i','l','.'};
printCharArray(c);
replaceSpace(c);
printCharArray(c);
}
}

4.6 객체의 소멸과 가비지 컬렉션
[예제 4-9] 가비지의 발생
package p216_GarbageEx;
public class p216_GarbageEx {
public static void main(String[] args) {
String a = new String("Good");
String b = new String("Bad");
String c = new String("Normal");
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println("------------------");
String d;
a = null;
d = c;
c = null;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}

4.7 접근 지정자
[예제 4-10] 멤버의 접근 지정자
package p224_AccessEx;
class Sample{
public int a;
private int b;
int c;
}
public class p224_AccessEx {
public static void main(String[] args) {
Sample sample = new Sample();
sample.a = 10;
sample.b = 10;
sample.c = 10;
}
}

4.8 static 멤버
[예제 4-11] static 멤버를 가진 Calc 클래스 작성
package p233_CalcEx;
class Calc{
public static int abs(int a) { return a>0?a:-a; }
public static int max(int a, int b) { return (a>b)?a:b; }
public static int min(int a, int b) { return (a>b)?b:a; }
}
public class p233_CalcEx {
public static void main(String[] args) {
System.out.println(Calc.abs(-5));
System.out.println(Calc.max(10, 8));
System.out.println(Calc.min(-3, -8));
}
}

[예제 4-12] static을 이용한 환율 계산기
package p234_StaticMember;
import java.util.Scanner;
class CurrencyConverter{
private static double rate;
public static double toDollar(double won) {
return won/rate;
}
public static double toKWR(double dollar) {
return dollar * rate;
}
public static void setRate(double r) {
rate = r;
}
}
public class p234_StaticMember {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("환율(1달러) >> ");
double rate = scanner.nextDouble();
CurrencyConverter.setRate(rate);
System.out.println("백만원은 $" + CurrencyConverter.toDollar(1000000) + "입니다.");
System.out.println("$100는 " + CurrencyConverter.toKWR(100) + "원입니다.");
scanner.close();
}
}

[Open Challenge - 끝말잇기 게임 만들기]
package p239_OpenChallenge;
import java.util.Scanner;
class WordGameApp {
private String[] names;
private Player[] players;
private int currentPlayerIndex;
public WordGameApp(int n) {
names = new String[n];
players = new Player[n];
for (int i = 0; i < n; i++) {
players[i] = new Player();
}
currentPlayerIndex = 0;
}
public void playGame() {
Scanner scanner = new Scanner(System.in);
String lastWord = "아버지"; // 첫 번째 단어를 아버지로 설정
System.out.println("시작하는 단어는 아버지입니다.");
while (true) {
System.out.print(names[currentPlayerIndex] + " >> ");
String word = players[currentPlayerIndex].getWordFromUser();
if (!isValidWord(word, lastWord)) {
System.out.println(names[currentPlayerIndex] + "이 졌습니다.");
break;
}
lastWord = word;
currentPlayerIndex = (currentPlayerIndex + 1) % names.length; // 다음 플레이어로 이동
}
scanner.close();
}
public void setNames(String[] names) {
this.names = names;
}
private boolean isValidWord(String word, String lastWord) {
if (lastWord.isEmpty()) {
return true; // 첫 번째 단어는 항상 유효
}
return lastWord.charAt(lastWord.length() - 1) == word.charAt(0);
}
}
class Player {
private Scanner scanner;
public Player() {
scanner = new Scanner(System.in);
}
public String getWordFromUser() {
return scanner.nextLine();
}
}
public class p239_OpenChallenge {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("끝말잇기 게임을 시작합니다.");
System.out.print("게임에 참가하는 인원은 몇명입니까? >> ");
int num = scanner.nextInt();
scanner.nextLine(); // 개행 문자 처리
WordGameApp gameApp = new WordGameApp(num);
String[] names = new String[num];
for (int i = 0; i < num; i++) {
System.out.print("참가자의 이름을 입력하세요 >> ");
names[i] = scanner.nextLine();
}
gameApp.setNames(names);
gameApp.playGame();
}
}

[연습문제 - 실습문제]
#1
package Quiz01;
class TV {
private String name;
private int inch;
private int price;
public TV(String name, int inch, int price) {
this.name = name;
this.inch = inch;
this.price = price;
System.out.println(name + "에서 만든 " + price + "만원짜리의 " + inch + "인치 TV");
}
}
public class Quiz01 {
public static void main(String[] args) {
TV tv = new TV("Samsung", 50, 300);
}
}

#2
package Quiz02;
class Cube{
private int width;
private int depth;
private int height;
public Cube(int width, int depth, int height) {
this.width = width;
this.depth = depth;
this.height = height;
}
int getVolume() {
return width * depth * height;
}
void increase(int width, int depth, int height) {
this.width++;
this.depth++;
this.height++;
}
boolean isZero() {
return width == 0 || depth == 0 || height == 0;
}
}
public class Quiz02 {
public static void main(String[] args) {
Cube cube = new Cube(1,2,3);
System.out.println("큐브의 부피는 " + cube.getVolume());
cube.increase(1 ,2, 3);
System.out.println("큐브의 부피는 " + cube.getVolume());
if(cube.isZero())
System.out.println("큐브의 부피는 0");
else
System.out.println("큐브의 부피는 0이 아님");
}
}

#3
package Quiz03;
import java.util.Scanner;
class Grade{
private String name;
private int java;
private int web;
private int os;
public Grade(String name, int java, int web, int os) {
this.name = name;
this.java = java;
this.web = web;
this.os = os;
}
String getName() {
return name;
}
int getAverage() {
return (java + web + os) / 3;
}
}
public class Quiz03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("이름, 자바, 웹프로그래밍, 운영체제 순으로 점수 입력 >> ");
String name = scanner.next();
int java = scanner.nextInt();
int web = scanner.nextInt();
int os = scanner.nextInt();
Grade st = new Grade(name, java, web, os);
System.out.print(st.getName() + "의 평균은 " + st.getAverage());
scanner.close();
}
}

#4
package Quiz04;
class Average{
private int[] avg;
private int idx;
public Average() {
avg = new int[10];
idx = 0;
}
void put(int n) {
avg[idx] = n;
idx++;
}
double getAvg() {
double sum = 0.0;
for(int i = 0; i<idx; i++) {
sum += avg[i];
}
return sum/idx;
}
void showAll() {
System.out.println("***** 저장된 데이터 모두 출력 *****");
for(int i = 0; i<idx ;i++) {
System.out.print(avg[i] + " ");
}
System.out.println();
}
}
public class Quiz04 {
public static void main(String[] args) {
Average avg = new Average();
avg.put(10);
avg.put(15);
avg.put(100);
avg.showAll();
System.out.print("평균은 " + avg.getAvg());
}
}

#5
package Quiz05;
class Song{
private String title;
private String singer;
private int year;
private String lang;
public Song(String title, String singer, int year, String lang) {
this.title = title;
this.singer = singer;
this.year = year;
this.lang = lang;
}
void show() {
System.out.println(year + "년 " + lang + "의 " + singer + "가 부른 " + title);
}
}
public class Quiz05 {
public static void main(String[] args) {
Song song = new Song("가로수 그늘 아래 서면", "이문세", 1988, "한국");
song.show();
}
}

#6
package Quiz06;
class Rectangle{
private int x, y, width, height;
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
void show() {
System.out.println("(" + x + ", " + y + ")에서 크기가 " + width + "x" + height + "인 사각형");
}
boolean isSquare() {
return width == height;
}
boolean contains(Rectangle r) {
return (r.x >= this.x) && (r.x+r.width <=this.x+this.width) && (r.y >= this.y) && (r.y + r.height <= this.y+this.height);
}
}
public class Quiz06 {
public static void main(String[] args) {
Rectangle a = new Rectangle(3,3,6,6);
Rectangle b = new Rectangle(4,4,2,3);
a.show();
if(a.isSquare()) System.out.println("a는 정사각형입니다.");
else System.out.println("a는 직사각형입니다.");
if(a.contains(b)) System.out.println("a는 b를 포함합니다.");
}
}

#7
package Quiz07;
class Memo{
private String name;
private String time;
private String content;
public Memo(String name, String time, String content) {
this.name = name;
this.time = time;
this.content = content;
}
boolean isSameName(Memo r) {
return this.name == r.name;
}
String getName() {
return this.name;
}
void show() {
System.out.println(name + ", " + time + " " + content);
}
int length() {
return this.content.length();
}
}
public class Quiz07 {
public static void main(String[] args) {
Memo a = new Memo("유송연", "10:10", "자바 과제 있음");
Memo b = new Memo("박채원", "10:15", "시카고로 어학 연수가요!");
Memo c = new Memo("김경미", "11:30", "사랑하는 사람이 생겼어요.");
a.show();
if(a.isSameName(b)) System.out.println("동일한 사람입니다.");
else System.out.println("다른 사람입니다.");
System.out.println(c.getName() + "가 작성한 메모의 길이는 " + c.length());
}
}

#8
package Quiz08;
class Account{
private int money; //잔고 금액
//계좌 생성
public Account(int money) {
this.money = money;
}
//잔금 확인
public int getBalance() {
return money;
}
//입금
public void deposit(int money) {
this.money += money;
}
//배열로 입금
public void deposit(int[] money) {
for(int i = 0; i<money.length; i++) {
this.money += money[i];
}
}
//출금
public int withdraw(int money) {
//인출하고 싶은 금액이 잔금보다 큰 경우 => 잔금만큼만 인출된다.
if (money > this.money) {
int totalmoney = this.money;
this.money = 0;
return totalmoney;
}
//인출하고 싶은 금액이 잔금보다 작은 경우
else {
this.money -= money;
return money;
}
}
}
public class Quiz08 {
public static void main(String[] args) {
Account a = new Account(100); //100원은 예금하면서 계좌 생성
a.deposit(5000); //5000원 예금
System.out.println("잔금은 " + a.getBalance() + "원입니다.");
int bulk[] = {100, 500, 200, 700 }; //1500원 입금
a.deposit(bulk); //bulk[] 배열에 있는 모든 돈 예금
System.out.println("잔금은 " + a.getBalance() + "원 입니다.");
int money = 1000; //인출하고자 하는 금액
int wMoney = a.withdraw(money); //1000원 인출 시도. wMoney는 실제 인출한 금액
if(wMoney < money)
System.out.println(wMoney + "원만 인출"); //잔금이 1000원보다 작은 경우
else
System.out.println(wMoney + "원 인출"); //잔금이 1000원보다 큰 경우
System.out.println("잔금은 " + a.getBalance() + "원입니다.");
}
}

#9
package Quiz09;
import java.util.Scanner;
class GuessGame{
private int people; //게임에 참가한 인원수
private int[] diff; // 숫자의 차이 저장
private int[] score; //점수 저장
private int[] number; //게임에 참가한 사람이 적은 숫자
private String[] name;
//생성자
public GuessGame(int people, String[] name) {
this.people = people;
this.diff = new int[people];
this.score = new int[people];
this.number = new int[people];
this.name = new String[people];
for(int i = 0; i<people; i++) {
this.name[i] = name[i];
score[i] = 0;
}
}
int GuessGame(int hiddenAnswer, int[] number) {
for(int i = 0; i<people; i++) {
diff[i] = Math.abs(hiddenAnswer - number[i]);
}
int idx = 0;
for(int i = 0; i<people; i++) {
if(diff[i] < diff[idx]) {
idx = i;
}
}
score[idx]++;
return idx;
}
void end() {
int max = 0;
for(int i = 0; i<people; i++) {
System.out.println(name[i] + ": " + score[i]);
if(score[max]< score[i]) max = i;
}
System.out.println(name[max] + "이 최종 승리하였습니다.");
}
}
public class Quiz09 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("*** 예측 게임을 시작합니다. ***");
System.out.print("게임에 참여할 선수 수 >> ");
int people = scanner.nextInt();
scanner.nextLine();
String[] name = new String[people];
for(int i = 0; i<people; i++) {
System.out.print("선수 이름 >> ");
name[i] = scanner.nextLine();
}
GuessGame game = new GuessGame(people, name);
int[] number = new int[people];
int hiddenAnswer;
while(true) {
hiddenAnswer = (int)(Math.random()*100+1);
System.out.println("1~100 사이의 숫자가 결정되엇습니다. 선수들은 맞추어 보세요.");
for(int i = 0; i<people; i++) {
System.out.print(name[i] + ">>");
number[i] = scanner.nextInt();
}
scanner.nextLine();
int idx = game.GuessGame(hiddenAnswer,number);
System.out.println("정답은 " + hiddenAnswer + ". " + name[idx] + "이 이겼습니다. 승점 1점 확보");
System.out.print("계속하려면 yes 입력 >> ");
String answer = scanner.nextLine();
if(answer.equals("no")) {
game.end();
break;
}
}
scanner.close();
}
}

#10
package Quiz10;
import java.util.Scanner;
class DayDiary{
private String memo;
public DayDiary() {
this.memo = " ... ";
}
void run(String memo) {
this.memo = memo;
}
String getMemo() {
return memo;
}
}
class MonthDiary{
private int year;
private int month;
private int answer;
private int day;
private DayDiary[] memo;
Scanner scanner = new Scanner(System.in);
public MonthDiary(int year, int month) {
this.year = year;
this.month = month;
memo = new DayDiary[30];
for (int i = 0; i < 30; i++) {
memo[i] = new DayDiary(); // 각 날짜에 대한 DayDiary 객체 생성
}
}
void run() {
System.out.println("***** " + year +"년 " + month + "월 다이어리 *****");
getMenu();
}
void write() {
System.out.print("날짜(1~30)와 텍스트(빈칸없이 4글자이하) >> ");
day = scanner.nextInt();
String text = scanner.nextLine();
memo[day - 1].run(text); // 0부터 시작하는 배열 인덱스
getMenu();
}
void show() {
int idx = 0;
for (int i = 0; i < 5; i++) {
for(int j = 0; j<7; j++) {
System.out.printf(memo[idx++].getMemo());
if(idx == 30) break;
}
System.out.println();
if(idx == 30) break;
}
getMenu();
}
void end() {
System.out.println("프로그램을 종료합니다.");
}
void getMenu() {
System.out.print("기록: 1, 보기: 2, 종료: 3 >> ");
answer = scanner.nextInt();
if(answer == 1) write();
else if(answer == 2) show();
else if(answer == 3) end();
}
}
public class Quiz10 {
public static void main(String[] args) {
MonthDiary monthDiary = new MonthDiary(2024, 10);
monthDiary.run();
}
}

#11
package Quiz11;
class ArrayUtil{
public static int[] concat(int[] a, int[] b) {
int idx = a.length + b.length;
int[] array = new int[idx];
for(int i = 0; i<idx; i++) {
if(i<a.length) array[i] = a[i];
else array[i] = b[i-a.length];
}
return array;
}
public static void print(int[] a) {
System.out.print("[");
for(int i = 0; i<a.length; i++) {
System.out.print(" " + a[i] +" ");
}
System.out.println("]");
}
}
public class Quiz11 {
public static void main(String[] args) {
int[] array1 = {1,5,7,9};
int[] array2 = {3,6,-1,100,77};
int[] array3 = ArrayUtil.concat(array1, array2);
ArrayUtil.print(array3);
}
}

#12
package Quiz12;
import java.util.Scanner;
class Dictionary{
private static String[] kor = {"사랑", "아기", "돈", "미래","희망"};
private static String[] eng = {"love", "baby", "money", "future", "hope"};
public static void kor2Eng(String word) {
int idx = 0;
for(; idx<kor.length; idx++) {
if(word.equals(kor[idx])) {
System.out.println(word + "은 " + eng[idx]);
break;
}
}
if(idx == kor.length) System.out.println(word + "는 저의 사전에 없습니다. ");
}
}
public class Quiz12 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("한영 단어 검색 프로그램입니다. ");
while(true) {
System.out.print("한글 단어? ");
String word = scanner.nextLine();
if(word.equals("그만")) break;
Dictionary.kor2Eng(word);
}
scanner.close();
}
}

#13
package Quiz13;
import java.util.Scanner;
class Concert{
private String[] S = {"...", "...", "...", "...", "...", "...", "...", "...", "...", "..." };
private String[] A = {"...", "...", "...", "...", "...", "...", "...", "...", "...", "..." };
private String[] B = {"...", "...", "...", "...", "...", "...", "...", "...", "...", "..." };
Scanner scanner = new Scanner(System.in);
//예약
void Reservation() {
System.out.print("좌석 구분 S(1), A(2), B(3) >> ");
int n = scanner.nextInt();
scanner.nextLine();
if(n == 1) {
System.out.print("S>> ");
for(int i = 0; i<10; i++) {
System.out.print(S[i] + " ");
}
System.out.println();
System.out.print("이름 >> ");
String name = scanner.nextLine();
System.out.print("번호 >> ");
int num = scanner.nextInt();
S[num-1] = name;
}
else if(n==2) {
System.out.print("A>> ");
for(int i = 0; i<10; i++) {
System.out.print(A[i] + " ");
}
System.out.println();
System.out.print("이름 >> ");
String name = scanner.nextLine();
System.out.print("번호 >> ");
int num = scanner.nextInt();
A[num-1] = name;
}
else {
System.out.print("B>> ");
for(int i = 0; i<10; i++) {
System.out.print(B[i] + " ");
}
System.out.println();
System.out.print("이름 >> ");
String name = scanner.nextLine();
System.out.print("번호 >> ");
int num = scanner.nextInt();
B[num-1] = name;
}
}
//조회
void inquiry() {
System.out.print("S>> ");
for(int i = 0; i<10; i++) System.out.print(S[i] + " ");
System.out.println();
System.out.print("A>> ");
for(int i = 0; i<10; i++) System.out.print(A[i] + " ");
System.out.println();
System.out.print("B>> ");
for(int i = 0; i<10; i++) System.out.print(B[i] + " ");
System.out.println();
System.out.println("<<< 조회를 완료하였습니다. >>>");
}
//취소
void Cancellation() {
System.out.print("좌석 S(1), A(2), B(3) >> ");
int n = scanner.nextInt();
scanner.nextLine();
if(n == 1) {
System.out.print("S>> ");
for(int i = 0; i<10; i++) {
System.out.print(S[i] + " ");
}
System.out.println();
System.out.print("이름 >> ");
String name = scanner.nextLine();
for(int i = 0; i<10; i++) {
if(S[i].equals(name)) S[i] = "...";
}
}
else if(n==2) {
System.out.print("A>> ");
for(int i = 0; i<10; i++) {
System.out.print(A[i] + " ");
}
System.out.println();
System.out.print("이름 >> ");
String name = scanner.nextLine();
for(int i = 0; i<10; i++) {
if(A[i].equals(name)) A[i] = "...";
}
}
else {
System.out.print("B>> ");
for(int i = 0; i<10; i++) {
System.out.print(B[i] + " ");
}
System.out.println();
System.out.print("이름 >> ");
String name = scanner.nextLine();
for(int i = 0; i<10; i++) {
if(B[i].equals(name)) B[i] = "...";
}
}
}
}
public class Quiz13 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("명품 콘서트홀 예약 시스템입니다.");
Concert concert = new Concert();
while(true) {
System.out.print("예약:1, 조회:2, 취소:3, 끝내기:4 >> ");
int n = scanner.nextInt();
if(n==1) concert.Reservation();
else if(n==2) concert.inquiry();
else if(n==3) concert.Cancellation();
else if(n==4) break;
}
scanner.close();
}
}

#14
package Quiz14;
class VArray {
private int[] array;
private int idx = 0;
private int length;
public VArray(int n) {
length = n;
array = new int[n];
}
void add(int num) {
if (idx >= length) {
resize(); // 배열 크기 증가
}
array[idx++] = num;
}
int capacity() {
return length;
}
int size() {
return idx;
}
void insert(int idx, int num) {
if (this.idx >= length) {
resize(); // 배열 크기 증가
}
for (int i = this.idx+1; i > idx; i--) {
array[i] = array[i - 1];
}
this.idx++;
array[idx] = num;
}
void remove(int idx) {
if(idx >= this.idx) return;
for (int i = idx; i < this.idx - 1; i++) {
array[i] = array[i + 1];
}
this.idx--;
}
void printAll() {
for (int i = 0; i < idx; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
private void resize() {
length *= 2; // 배열 크기를 두 배로 증가
int[] newArray = new int[length];
for (int i = 0; i < idx; i++) {
newArray[i] = array[i];
}
array = newArray;
}
}
public class Quiz14 {
public static void main(String[] args) {
VArray v = new VArray(5);
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
for (int i = 0; i < 7; i++)
v.add(i);
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
v.printAll();
v.insert(3, 300);
v.insert(5, 200);
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
v.printAll();
v.remove(10);
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
v.printAll();
for (int i = 50; i < 55; i++)
v.add(i);
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
v.printAll();
}
}
