책/멘토씨리즈 자바
[멘토씨리즈 자바] 15 기본 API 클래스 응용문제
yn98
2024. 7. 29. 17:45
1. 다음 코드에서 Object 클래스의 toString() 메서드를 재정의하여 User가 실행 결과와 같이 출력되도록 알맞은 코드를 작성해보세요.
package section15;
class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
// 코드작성
}
public class UserExample {
public static void main(String[] args) {
User user = new User("김철수", 22);
System.out.println(user);
}
}
작성한 코드
package section15;
class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
// 코드작성
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
public class UserExample {
public static void main(String[] args) {
User user = new User("김철수", 22);
System.out.println(user);
}
}
2. 다음 코드를 실행했을 때 콘솔 창에 출력되는 결과는 무엇입니까?
package section15;
public class StringCompareExample {
public static void main(String[] args) {
String sentence1 = "사과";
String sentence2 = new String("사과");
String sentence3 = "망고";
System.out.println(sentence1 == sentence2);
System.out.println(sentence2 == sentence3);
}
}
더보기
false
false
// .equals()를 써야 true
3. 다음 빈 칸에 문자열 '100'을 정수로 변환하는 코드를 삽입하여 더하기 기능을 완성해 보세요.
package section15;
public class ValueConvertExample {
public static void main(String[] args) {
String str = "100";
int data1 = 200;
int result = 0;
result = 100 + ??; // 요기
System.out.println("숫자 합 : "+ result);
}
}
더보기
Integer.parseInt(str);
문자열을 정수로 바꿔줌.
4. 1부터 30 사이의 숫자를 생성하여 숫자 맞추기 게임을 랜덤 함수를 사용해 만들어보세요. ( 단, 숫자를 맞출 수 있는 기회는 10번입니다.)
package section15;
import java.util.Scanner;
public class UpdownGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 0;
int matchValue = 0;
int value = 0;
matchValue = (int)(Math.random() * 30) +1;
while(count < 10) {
System.out.println("맞출 숫자 입력 : ");
value = scan.nextInt();
//이어서
}
}
}
package section15;
import java.util.Scanner;
public class UpdownGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 0;
int matchValue = 0;
int value = 0;
matchValue = (int)(Math.random() * 30) +1;
while(count < 10) {
System.out.println("맞출 숫자 입력 : ");
value = scan.nextInt();
//이어서
count++;
if (value < matchValue) {
System.out.println("UP! 더 큰 숫자를 입력하세요.");
} else if (value > matchValue) {
System.out.println("DOWN! 더 작은 숫자를 입력하세요.");
} else {
System.out.println("축하합니다! 숫자를 맞추셨습니다.");
break; // 숫자를 맞춘 경우 게임 종료
}
}
if (value != matchValue) {
System.out.println("정답은 " + matchValue + "였습니다. 게임 종료.");
}
scan.close();
}
}