[Java] 자바의 정석 6장 - 클래스를 이용한 연습문제

이 포스트는 클래스와 관련된 다양한 개념과 문제를 푸는 과정을 설명합니다.
Jan 10, 2024
[Java] 자바의 정석 6장 - 클래스를 이용한 연습문제

[6-1, 6-2]

notion image
notion image

SutdaCard.java

package ch06.example; public class SutdaCard { int num; boolean isKwang; public SutdaCard() { this(1, true); } public SutdaCard(int num, boolean isKwang) { this.num = num; this.isKwang = isKwang; } public String info() { return num + (isKwang ? "K" : ""); } }
 
 

[6-3, 6-4, 6-5]

notion image
notion image
notion image

Student.java

package ch06.example; public class Student { String name; int ban; int no; int kor; int eng; int math; public Student() { } public Student(String name, int ban, int no, int kor, int eng, int math) { this.name = name; this.ban = ban; this.no = no; this.kor = kor; this.eng = eng; this.math = math; } public int getTotal() { return kor + eng + math; } public float getAverage() { return Math.round(getTotal() / 3f * 10f) / 10f; } public String info() { return name + "," + ban + "," + no + "," + kor + "," + eng + "," + math + "," + getTotal() + "," + getAverage(); } }
 

[6-6]

notion image

Exercise6_6.java

package ch06.example; public class Exercise6_6 { static double getDistance(int x, int y, int x1, int y1) { return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1)); } public static void main(String[] args) { System.out.println(getDistance(1, 1, 2, 2)); } }

[6-7]

notion image

MyPoint.java

package ch06.example; public class MyPoint { int x; int y; public MyPoint(int x, int y) { this.x = x; this.y = y; } public double getDistance(int x1, int y1) { return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1)); } }

[6-8]

notion image

Answer

// 클래스변수: width,height // 인스턴스변수: kind,num // 지역변수: k,n,card

[6-9]

notion image

Answer

// weapon, armor: 모든 인스턴스가 공유해야 하기 때문

[6-10]

notion image

Answer

// b: 생성자는 객체 내의 필드를 초기화하기 위해 사용하는 것 // e: 생성자는 오버로딩 가능하다.

[6-11]

notion image

Answer

// b: this는 static(클래스 메서드) 안에서는 사용 불가능하다.

[6-12]

notion image

Answer

// c,d: 오버로딩은 파라미터의 개수, 타입이 다를 때 적용된다.

[6-13]

notion image

Answer

// b,c,d: a는 파라미터의 타입이 동일하므로 불가능하다.

[6-14]

notion image

Answer

// c: 인스턴스 변수는 디폴트, 명시적, 초기화블록, 생성자 순으로 초기화된다. // e: 클래스변수는 인스턴스를 만들기 이전 프로그램이 로딩되는 순간 메모리에 올라간다.

[6-15]

notion image

Answer

// a

[6-16]

notion image

Answer

// a: 로컬변수는 초기화가 없으면 사용이 불가능하다. // e: 힙 영역에는 인스턴스가 생성된다. 로컬변수는 스택에 생성된다.

[6-17]

notion image

Answer

// b: 나머지 메서드들은 종료된 것이 아니라 대기하고 있는 상태이다.

[6-18]

notion image

Answer

// a: static 변수의 초기화에 인스턴스 변수 사용 불가능 // b: static 메서드에 인스턴스 멤버 호출 불가능 // d: static 메서드에 인스턴스 멤버 호출 불가능

[6-19]

notion image

Answer

// ABC123 // ABC123

[6-20]

notion image

Exercise6_20.java

package ch06.example; public class Exercise6_20 { private static int[] shuffle(int[] arr) { for (int i = 0; i < arr.length; i++) { int random = (int) (Math.random() * arr.length); int tmp = arr[i]; arr[i] = arr[random]; arr[random] = tmp; } return arr; } public static void main(String[] args) { int[] original = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; System.out.println(java.util.Arrays.toString(original)); int[] result = shuffle(original); System.out.println(java.util.Arrays.toString(result)); } }

[6-21]

notion image
notion image

MyTv.java

package ch06.example; public class MyTv { boolean isPowerOn; int channel; int volume; final int MAX_VOLUME = 100; final int MIN_VOLUME = 0; final int MAX_CHANNEL = 100; final int MIN_CHANNEL = 1; void turnOnOff() { if(this.isPowerOn=true) { this.isPowerOn = false; }else { this.isPowerOn = true; } } void volumeUp() { if(this.volume<MAX_VOLUME) { this.volume++; } } void volumnDown() { if(this.volume>MAX_VOLUME) { this.volume++; } } void channelUp() { if(this.channel>MAX_CHANNEL) { this.channel = MIN_CHANNEL; }else { this.channel++; } } void channelDown() { if(this.channel<MIN_CHANNEL) { this.channel = MAX_CHANNEL; }else { this.channel--; } } }

[6-22]

notion image

Exercise6_22.java

package ch06.example; public class Exercise6_22 { private static boolean isNumber(String str) { return str.chars().allMatch(Character::isDigit); // for (int i = 0; i < str.length(); i++) { // if (str.charAt(i) != '0' && str.charAt(i) != '1' && // str.charAt(i) != '2' && str.charAt(i) != '3'&& // str.charAt(i) != '4' && str.charAt(i) != '5' && // str.charAt(i) != '6' && str.charAt(i) != '7'&& // str.charAt(i) != '8' && str.charAt(i) != '9') // { // return false; // } // } // return true; } public static void main(String[] args) { String str = "123"; System.out.println(str + "는 숫자입니까? " + isNumber(str)); str = "123o"; System.out.println(str + "는 숫자입니까? " + isNumber(str)); } }

핵심 키워드

  • chars() 함수는 문자열을 구성하고 있는 문자들의 아스키코드 값을 stream 형태로 뽑아준다.
  • allMatch() 함수는 모든 요소들이 주어진 조건을 만족하는지 조사한다.
  • 이중 콜론(::) 연산자는 람다 표현식 () -> {} 을 대체할 수 있다. 이 경우 코드에서 중복되는 파라미터를 줄이고 가독성을 높일 수 있다.
  • isDigit 함수는 char 값이 숫자인지 판단하여 true 또는 false 값을 리턴한다.
 

[6-23]

notion image
notion image

Exercise6_23.java

package ch06.example; public class Exercise6_23 { private static int max(int[] arr) { int max = 0; if(arr == null || arr.length == 0) { return -999999; } for(int i=0; i<arr.length; i++) { if(arr[i]>max) { max = arr[i]; } } return max; } public static void main(String[] args) { int[] data = {3,2,9,4,7}; System.out.println(java.util.Arrays.toString(data)); System.out.println("최대값:"+max(data)); System.out.println("최대값:"+max(null)); System.out.println("최대값:"+max(new int[] {})); } }

[6-24]

notion image

Exercise6_24.java

package ch06.example; public class Exercise6_24 { private static int abs(int value) { return Math.abs(value); } public static void main(String[] args) { int value = 5; System.out.println(value + "의 절대값:" + abs(value)); value = -10; System.out.println(value + "의 절대값:" + abs(value)); } }

[이것이 자바다 5장 연습문제 변형]

Student1.java

package ch06.example; public class Student1 { String name; String height; Student1(String name, String height){ this.name = name; this.height = height; } public String getName() { return name; } public String getHeight() { return height; } }

Student1Practice.java

package ch06.example; import java.util.*; public class Student1Practice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // 학급 수 설정 System.out.printf("학급 수를 입력하세요 --> "); int classNum = scan.nextInt(); // 입력받은 수만큼 총 학급 수 설정 // 객체의 배열을 생성 시 객체 자체가 아닌 객체를 참조하는 배열이 생성됨. // 따라서 student 인스턴스는 Student1 객체의 배열에 대한 참조를 담을 수 있는 배열을 생성한 것. Student1[][] student = new Student1[classNum][]; // 학급 수 만큼 학생 키 설정 for (int i = 0; i < classNum; i++) { System.out.printf("%d반 학생 수를 입력하세요 --> ", i + 1); int studentNum = scan.nextInt(); scan.nextLine(); // 입력받은 수 만큼 각 학급의 학생 수 설정 student[i] = new Student1[studentNum]; // 열의 크기 만큼 학생의 키 설정 반복 for (int j = 0; j < studentNum; j++) { System.out.println("---------------입력---------------"); System.out.printf("%d반의 %d번 학생의 이름과 키를 공백으로 구분해서 입력하세요 --> ", i + 1, j + 1); String studentInfo = scan.nextLine(); // 입력받은 이름과 키를 공백으로 구분 String[] info = studentInfo.split(" "); String name = info[0]; String height = info[1]; // 분리한 이름과 키를 ()를 붙여서 저장 student[i][j] = new Student1(name, height); } } // 각 반 학생의 키 출력 for (int i = 0; i < student.length; i++) { System.out.printf("%d반 학생들의 키: ", i + 1); for (int j = 0; j < student[i].length; j++) { if (j == student[i].length - 1) { System.out.println(student[i][j].getName()+"("+student[i][j].getHeight()+")"); } else { System.out.print(student[i][j].getName()+"("+student[i][j].getHeight()+")" + ", "); } } } } }
 

결론

해당 문제들을 풀면서 allMatch() 함수, 이중 콜론 연산자, isDigit() 함수와 같이 처음 보는 문법을 익힐 수 있었다. 또한 클래스를 응용할 수 있는 문제들에 대해서도 알 수 있었다.
 
Share article
RSSPowered by inblog