자바의 정석 연습문제 ch 9 java.lang 패키지와 유용한 클래스
자바의 정석 3판 기초판 연습문제
https://github.com/castello/javajungsuk3
GitHub - castello/javajungsuk3: soure codes and ppt files of javajungsuk 3rd edition
soure codes and ppt files of javajungsuk 3rd edition - GitHub - castello/javajungsuk3: soure codes and ppt files of javajungsuk 3rd edition
github.com
[9-1] 다음과 같은 실행결과를 얻도록 SutdaCard클래스의 equals()를 멤버변수인 num, isKwang의 값을 비교하도록 오버라이딩하고 테스트 하시오.
public class Ex9_1 {
public static void main(String[] args) {
Sutdacard c1 = new Sutdacard(3, true);
Sutdacard c2 = new Sutdacard(3, true);
System.out.println("c1=" + c1);
System.out.println("c2=" + c2);
System.out.println("c1.equals(c2) :" + c1.equals(c2));
}
}
class Sutdacard {
int num;
boolean isKwang;
Sutdacard() {
this(1, true);
}
Sutdacard(int num, boolean isKwang) {
this.num = num;
this.isKwang = isKwang;
}
public boolean equals(Object obj) {
// 1)
}
public String toString() {
return num + (isKwang ? "K" : "");
}
}
public boolean equals(Object obj) {
// 1)
if(obj instanceof Sutdacard) {
Sutdacard c = (Sutdacard)obj;
return num==c.num && isKwang==c.isKwang;
}
return false;
}
[9-2] 다음과 같은 실행결과를 얻도록 Point3D클래스의 equals()를 멤버변수인 x, y, z 의 값을 비교하도록 오버라이딩하고, toString()은 실행결과를 참고해서 적절히 오버라이 딩하시오.
public class Ex9_2 {
public static void main(String[] args) {
Point3D p1 = new Point3D(1, 2, 3);
Point3D p2 = new Point3D(1, 2, 3);
System.out.println(p1);
System.out.println(p2);
System.out.println("p1==p2?" + (p1==p2));
System.out.println("p1.equals(p2)?" + p1.equals(p2));
}
}
class Point3D{
int x, y, z;
Point3D() {
this(0, 0, 0);
}
Point3D(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public boolean equals(Object obj) {
// 1) 인스턴스 변수 x, y, z 를 비교하도록 오버라이딩
}
public String toString() {
// 2) 인스턴슨 변수 x, y, z의 내용을 출력하도록 오버라이딩
}
}
public boolean equals(Object obj) {
// 1) 인스턴스 변수 x, y, z 를 비교하도록 오버라이딩
if(obj instanceof Point3D) {
Point3D p = (Point3D)obj;
return p.x==x && p.y==y && p.z==z;
}
return false;
}
public String toString() {
// 2) 인스턴슨 변수 x, y, z의 내용을 출력하도록 오버라이딩
return "[" + x + "," + y + "," + z +"]";
}
[9-3] 다음과 같은 실행결과가 나오도록 코드를 완성하시오.
String fullPath = "c:\\jdk1.8\\work\\PathSeparateTest.java";
String path = "";
String fileName = "";
// 1)
System.out.println("fullPath: " + fullPath);
System.out.println("path: " + path);
System.out.println("fileName: " + fileName);
// 1)
int pos = fullPath.lastIndexOf("\\");
if(pos!=-1) {
path = fullPath.substring(0, pos);
fileName = fullPath.substring(pos+1);
}
/*
lastIndexOf 마지막 구분자를 찾아 인덱스 반환
찾는 문자열이 없으면 -1 반환하기 때문에 조건문 사용해 확인 필요
subString은 문자열을 잘라주는 메서드로 매개변수를 한개만 전달하면 매개변수부터 끝까지 잘라줌
subString(시작, 끝) 주의할 점은 끝인덱스 문자를 포함하지 않는다는 것!
*/
[9-4] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.
메서드명 : printGraph
기능 : 주어진 배열에 담긴 값만큼 주어진 문자를 가로로 출력한 후, 값을 출력
반환타입 : 없음
매개변수 : int[] dataArr - 출력할 그래프의 데이터
char ch - 그래프로 출력할 문자
public class Ex9_4 {
static void printGraph(int[] arr, char ch) {
// 1)
}
public static void main(String[] args) {
printGraph(new int[] {3, 7, 1, 4}, '*');
}
}
static void printGraph(int[] arr, char ch) {
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i]; j++) {
System.out.print(ch);
}
System.out.println(arr[i]);
}
}
[9-5] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.
[Hint] String클래스의 indexOf(String str, int fromIndex)를 사용할 것
메소드명 : count
기능 : 주어진 문자열 src에 찾으려믄 문자열 target이 몇 번 나오는지 세어서 반환
반환타입 : int
매개변수 : Sring src, String target
public static int count(String src, String target) {
int count = 0; // 찾은 횟수
int pos = 0; // 찾기 시작할 위치
// 1)
}
public static void main(String[] args) {
System.out.println(count("12345AB12AB345AB", "AB"));
System.out.println(count("12345", "AB"));
}
public static int count(String src, String target) {
int count = 0; // 찾은 횟수
int pos = 0; // 찾기 시작할 위치
// 1)
while(true) {
pos = src.indexOf(target, pos);
if(pos != -1) {
count++;
pos += target.length(); // pos의 위치를 다음 단어로 이동
} else {
break;
}
}
return count;
}
[9-6] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.
메서드명 : fillZero
기능 : 주어진 문자열로 주어진 길이의 문자열로 만들고, 왼쪽 빈 공간은 '0'으로 채운다. 만일 주어진 문자열이 null이거나 문자열의 길이가 length의 값과 같으면 그대로 반환, 주어진 length의 값이 0보다 같거나 작은 값이면 빈문자열""을 반환한다.
반환타입 : String
매개변수 : String src - 변환할 문자열, int length - 변환한 문자열의 길이
public class Ex9_6 {
public static String fillZero(String src, int length) {
/*
* src가 null이거나 src.length가 length와 같으면 src 그대로 반환
* length의 값이 0보다 같거나 작으면 빈 문자열 "" 반환
* src의 길이가 length의 값보다 크면 src를 length만큼 잘라서 반환
* 길이가 length인 char배열 생성
* 위에서 생성한 char배열을 '0'으로 채운다
* src에서 문자배열을 뽑아내서 위에서 생성한 배열에 복사한다.
* 생성한 배열로 String을 생성해 반환
* */
if(src == null || src.length() == length) { //src가 null이거나 src.length가 length와 같으면 src 그대로 반환
return src;
} else if(length <= 0) { //length의 값이 0보다 같거나 작으면 빈 문자열 "" 반환
return "";
} else if(src.length() > length) { //src의 길이가 length의 값보다 크면 src를 length만큼 잘라서 반환
return src.substring(0, length);
}
// 길이가 length인 char배열 생성
char[] chArr = new char[length];
//위에서 생성한 char배열을 '0'으로 채운다
for(int i = 0; i < chArr.length; i++) {
chArr[i] = '0';
}
//src에서 문자배열을 뽑아내서 위에서 생성한 배열에 복사한다.
System.arraycopy(src.toCharArray(), 0, chArr, length-src.length(), src.length());
/*
* toCharArray 문자열을 char[]에 한 글자씩 넣어주는 메서드
* arraycopy(복사하고자하는 소스, 소스의 시작위치, 복사 대상, 복사본 시작 위치, 복사할 길이)
* */
//생성한 배열로 String을 생성해 반환
return new String(chArr);
// char[]을 합쳐서 하나의 String으로
}
public static void main(String[] args) {
String src = "12345";
System.out.println(fillZero(src, 10));
System.out.println(fillZero(src, -1));
System.out.println(fillZero(src, 3));
}
}
[9-7] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.
[Hint] String클래스의 indexOf()를 사용할 것
메서드명 : contains
기능 : 첫번째 문자열 src에 두번째 문자열 target이 포함되어있는지 확인한다. 포함되어 있으면 true, 없으면 false 반환
반환타입 : boolean
매개변수 : String src, String target
public class Ex9_7 {
public static boolean contains(String src, String target) {
return src.indexOf(target) != -1;
}
public static void main(String[] args) {
System.out.println(contains("12345", "23"));
System.out.println(contains("12345", "67"));
}
}
[9-8] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.
[Hint] Math.round()와 Math.pow()를 이용하라.
메서드명 : round
기능 : 주어진 값을 반올림하여, 소수점이하 n자이의 값을 반환한다. 예를 들어 n의 값이 3이면 소수점 4번째 자리에서 반올림하여 소수점이하 3자리의 수를 반환한다.
반환타입 : double
매개변수 : double d - 변환할 값, int n - 반올림한 결과의 소수점 자리
public class Ex9_8 {
public static double round(double d, int n) {
return Math.round(d * Math.pow(10, n)) / Math.pow(10, n);
// Math.pow 제곱함수(밑수, 지수)
// Math.round 반올림함수 소수점 첫번째 자리 반올림
}
public static void main(String[] args) {
System.out.println(round(3.1415, 1));
System.out.println(round(3.1415, 2));
System.out.println(round(3.1415, 3));
System.out.println(round(3.1415, 4));
System.out.println(round(3.1415, 5));
}
}
[9-9] 다음과 같이 정의된 메서드를 작성하고 테스트하시오
[힌트] StringBuffer와 String클래스의 charAt(int i)과 indexOf(int ch)를 사용하라.
메서드명 : delChar
기능 : 주어진 문자열에서 금지된 문자들을 제거하여 반환한다.
반환타입 : String
매개변수 : String src - 반환할 문자열, String delCh - 제거할 문자들로 구성된 문자열
public static String delChar(String src, String delCh) {
StringBuffer sb = new StringBuffer(src.length());
for(int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
// src문자열을 하나씩 분리
if(delCh.indexOf(c) == -1) {
// 지울 문자열에 c가 포함되어있지 않으면 buffer에 추가
sb.append(c);
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println("(1!2@3^4~5)" + " -> " + delChar("(1!2@3^4~5)", "~!@#$%^&*()"));
System.out.println("(1 2 3 4\t5)" + " -> " + delChar("(1 2 3 4\t5)", " \t"));
}
[9-10] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.
메서드명 : format
기능 : 주어진 문자열을 지정된 크기의 문자열로 변환한다. 나머지 공간은 공백으로 채운다.
반환타입 : String
매개변수 : String str - 반환할 문자열, int length - 변환된 문자열의 길이, int allignment -변환된 문자열 정렬조건(0왼, 1가운데, 2오)
public class Ex9_10 {
public static String format(String str, int length, int alignment) {
// length가 str 길이보다 작으면 length 만큼 자름
if(length - str.length() < 0) {
return str.substring(0, length);
}
// str 문자 배열로 변경
char[] strArr = str.toCharArray();
char[] arr = new char[length];
// 공백 넣기
for(int i = 0; i < arr.length; i++) {
arr[i] = ' ';
}
// 정렬
switch(alignment) {
case 0:
default:
System.arraycopy(strArr, 0, arr, 0, strArr.length);
break;
case 1:
System.arraycopy(strArr, 0, arr, (length - str.length())/2, strArr.length);
break;
case 2:
System.arraycopy(strArr, 0, arr, length - str.length(), strArr.length);
break;
}
return new String(arr);
}
public static void main(String[] args) {
String str = "가나다";
System.out.println(format(str, 7, 0));
System.out.println(format(str, 7, 1));
System.out.println(format(str, 7, 2));
}
}
[9-12] 다음과 같이 정의된 메서드를 작성하고 테스트하시오.
[힌트] Math.random()과 절대값을 반환하는 Math.abs(int a), 그리고 둘 중 작은 값을 반환하는 Math.min(int a, int b)를 사용하라.
메서드명 : getRand
기능 : 주어진 범위에 속한 임의의 정수값을 반환한다.(양쪽 경계값 모두 범위에 포함), from값이 to의 값보다 클 경우도 처리되어야 한다.
반환타입 : int
매개변수 : int from - 범위의 시작값, int to - 범위의 끝값
public class Ex9_12 {
public static int getRand(int from, int to) {
return (int)(Math.random() * Math.abs(to-from -1)) + 1 + Math.min(from, to);
}
public static void main(String[] args) {
for(int i = 0; i < 20; i++) {
System.out.println(getRand(1, -3));
}
}
}
[9-13] 다음은 하나의 긴 문자열(source) 중에서 특정 문자열과 일치하는 문자열의 개수 를 구하는 예제이다. 빈 곳을 채워 예제를 완성하시오.
public class Ex9_13 {
public static void main(String[] args) {
String src = "aabbccAABBCCaa";
System.out.println(src);
System.out.println("aa를" + stringCount(src, "aa") + "개 찾았습니다.");
}
static int stringCount(String src, String key) {
return stringCount(src, key, 0);
}
static int stringCount(String src, String key, int pos) {
int count = 0;
int index = 0;
if(key == null | key.length() == 0) {
return 0;
}
// 1)
return count;
}
}
// 1)
// src에 key와 일치하는 부분의 위치 index가 -1이 아니면 계속 반복
while((index = src.indexOf(key, pos)) != -1) {
count++; // 같은 문자열 찾으면 증가
pos = index + key.length(); // 검색 시작 위치 변
}