1. 반지름이 같은 Circle 객체를 모두 동일한 종류로 취급하는 Circle 클래스를 작성하고 다음 프로그램으로 검증하라.
📢주어진 조건📢
public class CircleTest {
public static void main(String[] args) {
Circle c1 = new Circle(3);
Circle c2 = new Circle(3);
if (c1.equals(c2)) {
System.out.println("c1과 c2는 같다.");
} else
System.out.println("c1과 c2는 다르다");
}
}
🧤정답🧤
public class Circle {
int num;
public Circle(int num) {
this.num = num;
}
// equals()를 오버라이딩하면 hashCode()도 오버라이딩 해야한다.
public int hashCode() {
// Objects클래스는 객체와 관련된 유용한 메서드를 제공하는 유틸 클래스
return Objects.hash(num); // 매개변수가 가변인자라서 호출시 지정하는 값의 개수가 정해져있지 않다.
}
@Override
public boolean equals(Object obj) {
// 가장 먼저 ==연산자를 이용해 equals 인자가 자기 자신인지 검사해라
if (this == obj)
return true;
// instanceof 연산자를 사용하여 인자의 자료형이 정확한지 검사
if (!(obj instanceof Circle))
return false;
// equals의 인자를 정확한 자료형으로 변환
Circle confignation = (Circle) obj;
// 필드 값이 인자로 주어진 객체의 해당 필드와 일치하는지 확인
return num == confignation.num;
}
}
2. 다음 프로그램과 실행 결과에 적합한 Student 클래스를 작성하라.
📢주어진 조건📢
public class StudentTest {
public static void main(String[] args) {
System.out.println(new Student("김삿갓"));
System.out.println(new Student("홍길동"));
}
}
📢주어진 결과값📢
학생[김삿갓]
학생[홍길동]
🧤정답🧤
public class Student {
String name;
public Student(String name) {
this.name = name;
}
public String toString() {
String s = MessageFormat.format("학생[{0}]", name);
return s;
}
}
public class StudentTest {
public static void main(String[] args) {
System.out.println(new Student("김삿갓"));
System.out.println(new Student("홍길동"));
}
}
3. Calender 클래스를 사용해 연월일을 비롯한 날짜 정보를 출력하려고 한다. 다음 프로그램을 완성하라.
📢주어진 조건📢
public class CalendarTest {
public static void main(String[] args) {
String[] weekName = { "일", "월", "화", "수", "목", "금", "토" };
String[] noonName = { "오전", "오후" };
Calendar c = Calendar.getInstance();
// 코드 추가
System.out.println(year + "년 " + month + "월 " + day + "일 ");
System.out.println(week + "요일 " + noon);
System.out.println(hour + "시 " + minute + "분 " + second + "초 ");
}
}
📢주어진 결과값📢
2017년 6월 15일
목요일 오후
3시 33분 40초
🧤정답🧤
public class CalendarTest {
public static void main(String[] args) {
String[] weekName = { "일", "월", "화", "수", "목", "금", "토" };
String[] noonName = { "오전", "오후" };
Calendar c = Calendar.getInstance();
c.set(2017, 6, -1, 15, 15, 33, 40)
// c.set(Calendar.YEAR, 2017);
// c.set(Calendar.MONTH, 6);
// c.set(Calendar.DATE, 15);
// c.set(Calendar.HOUR_OF_DAY, 15);
// c.set(Calendar.MINUTE, 33);
// c.set(Calendar.SECOND, 40);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DATE);
String week = weekName[Calendar.THURSDAY - 1];
String noon = noonName[Calendar.PM];
int hour = c.get(Calendar.HOUR);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
System.out.println(year + "년 " + month + "월 " + day + "일 ");
System.out.println(week + "요일 " + noon);
System.out.println(hour + "시 " + minute + "분 " + second + "초 ");
}
}
4. 주사위 게임용 Dice 클래스를 작성하라.
📢주어진 조건 1📢
주사위를 굴리면 1~6 사이의 정수만 임의로 반환하므로 Math 클래스의 random() 메서드를 사용해 숫자를 임의로 반환하면 된다.
📢주어진 조건 2📢
public class DiceTest {
public static void main(String[] args) {
System.out.println(new Dice().roll());
}
}
📢주어진 결과값📢
4
🧤정답🧤
public class DiceTest {
public static void main(String[] args) {
System.out.println(new Dice().roll());
}
}
public class Dice {
int roll() {
return (int) (Math.random() * 6) + 1;
}
}
5. String, StringBuilder, StringBuffer 클래스는 모두 문자열을 처리하는 클래스이다. 다음 프로그램처럼 세 가지 타입에 모두 가능한 show() 메서드를 작성하라.
📢주어진 조건 1📢
자바 API를 참조해 String, StringBuilder, StringBuffer의 부모 타입을 찾는다.
📢주어진 조건 2📢
public class StringTest {
public static void main(String[] args) {
show(new String("멘붕"));
show(new StringBuilder("meltdown"));
show(new StringBuffer("!@#"));
show(new Date()) // 오류 발생
}
}
📢주어진 결과값📢
멘붕
meltdown
!@#
🧤정답🧤
public class StringTest {
public static void main(String[] args) {
show(new String("멘붕"));
show(new StringBuilder("meltdown"));
show(new StringBuffer("!@#"));
// show(new Date()) // 오류 발생
}
public static void show(Object o) {
System.out.println(o);
}
// 하나의 메서드를 여러개를 만들어 매개변수 타입을 다르게 주는 것을 이용
// public static void show(StringBuffer stringGab) {
// System.out.println(stringGab);
// }
//
// public static void show(String stringBufferGab) {
// System.out.println(stringBufferGab);
// }
//
// public static void show(StringBuilder stringBufferGab) {
// System.out.println(stringBufferGab);
// }
}