다음과 같이 구구단을 출력하는 프로그램을 작성하여야 한다.

2*1=2	3*1=3	4*1=4	
2*2=4	3*2=6	4*2=8	
2*3=6	3*3=9	4*3=12	

5*1=5	6*1=6	7*1=7	
5*2=10	6*2=12	7*2=14	
5*3=15	6*3=18	7*3=21	

8*1=8	9*1=9	
8*2=16	9*2=18	
8*3=24	9*3=27

이를 위해서는 다음과 같은 반복문을 만족하도록 x와 y의 규칙을 정하여야 한다.

package chap04.verify;

public class Exercise4_12 {

	public static void main(String[] args) {
		for(int i = 1; i < 10;i++) {
			for(int j = 1;j <= 3;j++) {
				int x = ?;
				int y = ?;
				if(x == 10) {	// 10단은 제외
					break;
				}
				System.out.print(x + "*" + y + "=" + x * y + "\t");
			}
			System.out.println();
			if(i % 3 == 0) {
				System.out.println();
			}
		}
	}
}

이를 위해 i, j와 x, y의 관계표를 작성하면 다음과 같다.

i, j와 x, y의 연관관계를 분석해 보면 위와 같은 관계식이 도출된다.

이를 코드로 나타내면 다음과 같다.

package chap04.verify;

public class Exercise4_12 {

	public static void main(String[] args) {
		for(int i = 1; i < 10;i++) {
			for(int j = 1;j <= 3;j++) {
				int x = 3*((i-1)/3)+j+1;
				int y = (i % 3 == 0)? 3 : i % 3;
				if(x == 10) {
					break;
				}
				System.out.print(x + "*" + y + "=" + x * y + "\t");
			}
			System.out.println();
			if(i % 3 == 0) {
				System.out.println();
			}
		}
	}
}

실행결과는 다음과 같다.

'자바' 카테고리의 다른 글

디자인 패턴 - 옵저버 패턴  (0) 2022.07.11
디자인 패턴 -전략 패턴  (0) 2022.07.10
자바의 정석 연습문제 풀이 3-1 중  (0) 2022.06.29
자바 protected 접근 제어자  (0) 2017.05.18
자바 라벨 제어문  (0) 2017.05.12
Posted by 세상을 살아가는 사람
,

Posted by 세상을 살아가는 사람
,

다음 연산의 결과를 적으시오.

[연습문제] /ch3/Exercise3_1.java

class Exercise3_1 {
  public static void main(String[] args) {
    int x = 2;
    int y = 5;
    char c = 'A'; // 'A' 의 문자코드는 65
    System.out.println(1 + x << 33);
    System.out.println(y >= 5 || x < 0 && x > 2);
    System.out.println(y += 10 - x++);
    System.out.println(x+=2);
    System.out.println( !('A' <= c && c <='Z') );
    System.out.println('C'-c);
    System.out.println('5'-'0');
    System.out.println(c+1);
    System.out.println(++c);
    System.out.println(c++);
    System.out.println(c);
  }
}

 

- System.out.println(c+1);

  + c+1은 정수값이며, 이를 출력하면 66이 된다. 왜냐하면 char + int = int로 자동 형 변환되므로 int가 결과로 도출된다.

- System.out.println(++c);

  + ++c는 char가 되며, 'B'가 된다. 왜냐하면 CPU내에서는 int로 동작되지만 이 값이 char로 저장되어야 하며, 이를 출력하는 것이므로 'B'가 된다.

- System.out.println(c++);

  + c는 'B'이므로 'B'가 출력이 된다. 이후 c는 증가하여 'C'가 된다.

- System.out.println(c);

  + c가 'C'이므로 'C'가 출력된다.

Posted by 세상을 살아가는 사람
,