목차
[신용권의 이것이 자바다 챕터 4 조건문과 반복문 확인 문제 풀이]
문제1 답:
#조건문의 종류: if, switch
#반복문의 종류: for, while, do-while
문제 2 답: 2번
switch 문에는 double이 올 수 없다. 가능한 타입들은 : byte, char, short, int, long, String 뿐이다.
문제3 답:
public class Ex03 {
public static void main(String[] args) {
int sum=0;
for (int ii=1; ii<=100; ii++) {
if (ii%3 == 0) {
sum+=ii;
}
}
System.out.println(sum);
}
}
문제4 답:
public class Ex04 {
public static void main(String[] args) {
while (true) {
int A = (int)(Math.random()*6) + 1;
int B = (int)(Math.random()*6) + 1;
if (A+B == 5) {
break;
}
else {
System.out.format("(%d,%d)\n",A,B);
}
}
}
}
- Math.random() 메소드는 0.0이상 1.0미만의 double 타입 난수 하나를 뱉는다. (0.0 포함, 1.0 미포함 주의)
즉, 0.999999999*6 을 해보았자 6미만이고, 0.0*6을 해보았자 1이 나오지 않는다. 그래서 +1을 끝에 해줌.
문제5 답:
public class Ex05 {
public static void main(String[] args) {;
for (int x = 1; x<=15; x++) {
for (int y = 1; y<=12; y++) {
if (4*x+5*y==60) {
System.out.format("(%d,%d)\n",x,y);
}
}
}
}
}
문제 제대로 안읽고, 그냥 if 절이랑 %,/ 연산써서 풀려다가.... 중첩 포문으로 풀란 소리에... 다시 짠 코드 ㅋㅋ
문제6 답:
public class Ex06 {
public static void main(String[] args) {
for (int ii = 1; ii<=5; ii++) {
for (int jj=0;jj<ii;jj++) {
System.out.print("*");
}
System.out.println("");
}
}
}
헷. 별찍기 문제는 백준에서 너무 길고 닦여졌다.
문제 7 답:
import java.util.Scanner;
public class Ex07 {
public static void main(String[] args) {
boolean run = true;
int balance = 0;
Scanner sc = new Scanner(System.in);
while(run) {
System.out.println("-------------------------------------");
System.out.println("1.예금 | 2.출금 | 3.잔고 | 4.종료");
System.out.println("-------------------------------------");
System.out.print("선택> ");
int menuNum = sc.nextInt();
switch(menuNum) {
case 1:
System.out.print("예금액>");
balance += scanner.nextInt();
break;
case 2:
System.out.print("출금액>");
balance -= scanner.nextInt();
break;
case 3:
System.out.print("잔고>");
System.out.println(balance);
break;
case 4:
run = false;
break;
}
System.out.println();
}
System.out.println("프로그램 종료");
}
}
※ 출처: 이것이 자바다 신용권의 Java 프로그래밍 정복 - 한빛미디어