[Java] 자바의 정석
자바의 정석 / Chap9) java.lang패키지와 유용한 클래스 - 연습문제
sweetychocoding
2023. 9. 21. 09:12
728x90
9-1)
package j17_Lambda;
import java.util.Arrays;
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) {
if (obj instanceof SutdaCard) {
SutdaCard c = (SutdaCard)obj;
return num == c.num && isKwang == c.isKwang;
} else {
return false;
}
}
public String toString() {
return num + (isKwang ? "k" : "");
}
}
public class Ex_chapter9 {
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("cl.equals(c2) : " + c1.equals(c2));
}
}

9-2)
package j17_Lambda;
class Point3D {
int x, y, z;
Point3D (int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
Point3D() {
this(0 ,0 ,0);
}
public boolean equals(Object obj) {
if (obj instanceof Point3D) {
Point3D p = (Point3D) obj;
return x == p.x && y == p.y && z == p.z;
} else {
return false;
}
}
public String toString() {
return "[" + x + ", " + y + ", " + z + "]";
}
}
public class Ex_chapter9 {
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)));
}
}

9-3)
package example01;
public class Ex_chapter9 {
public static int count(String src, String target) {
int count = 0;
int pos = 0;
while (true) {
int res = src.indexOf(target, pos);
if (res == -1) {
return count;
} else {
count++;
pos += target.length();
}
return count;
}
}
public static void main(String[] args) {
System.out.println(count("12345AB12AB345AB", "AB"));
System.out.println(count("12345", "AB"));
}
}
내가 처음 작성한 코드이다.
res라는 변수를 추가해서 target의 위치를 반환받고 있다.
하지만 애초에 따로 변수를 선언하지 않고 처음부터 pos에 첫 위치를 담으면 되는 것이었다.
아래는 수정한 코드이다.
package example01;
public class Ex_chapter9 {
public static int count(String src, String target) {
int count = 0;
int pos = 0;
while (true) {
pos = src.indexOf(target, pos);
if (pos != -1) {
count++;
pos += target.length();
} else {
break;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(count("12345AB12AB345AB", "AB"));
System.out.println(count("12345", "AB"));
}
}
9-4)
728x90