[Java] 1부터 50까지의 369게임 만들기

JTI·2022년 10월 12일
0

📌 Code list

목록 보기
18/55
post-thumbnail

369게임을 만들어보자.
369게임은 숫자에 3,6,9가 포함되어 있으면 3,6,9 개수만큼 박수치는 게임이다.
1부터 50까지의 정수에 대하여 369게임을 실행한다.

✏️count를 이용한 방법

public class Game {

	public static void main(String[] args) {
		
		for (int i = 1; i <= 50; i++) {
			int a = i / 10; // 10의자리
			int b = i % 10; // 1의 자리
			int count = 0;
			
			if (a == 3 || a == 6 || a == 9) { // 10의 자리가 3,6,9일 때 카운트.
				count ++
			}
			if (b == 3 || b == 6 || b == 9) {
				count ++
			}
			if (count == 2) { // 10의 자리 1의자리 둘다 카운트 되었을 때, 짝짝.
				System.out.print("짝짝 ");
			} else if (count == 1) {
				System.out.print("짝 ");
			} else {
				System.out.print(i + " ");
			}
			
		}

	}

}

이런식으로 10의 자리와 1의 자리를 각각 구해준다.

int a = i / 10; // 10의자리
int b = i % 10; // 1의 자리

✏️ boolean을 이용한 방법

public class Game {
	public static void main(String[] args) {
		for (int i = 1; i <= 50; i++) {
			boolean a = false;
			boolean b = false;
			
			int result = i % 10;
			if (result == 3 || result == 6 || result == 9) {
				a = true;
			}

			result = i /10;
			if (result == 3 || result == 6 || result == 9) {
				b = true;
			}
			if (a && b == true) { // true값이 두 번 나왔을 때, 짝짝.
				System.out.print("짝짝 ");
			} else if (a || b == true) { // true가 한 번만 나왔을 때, 짝.
				System.out.print("짝 ");
			} else {
				System.out.print(i + " ");
			}
		}
	}
}
profile
Fill in my own colorful colors🎨

0개의 댓글