문제1) 두개의 주사위를 던졌을때 나오는 눈을 (눈1, 눈2) 형태로 출력하고, 눈의 합이 10이면 실행을 종료하는 코드 작성 (Math.random() 메소드)

 

public class Exam {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int count = 0;
		while(true) {
			count++; // 주사위를 던진 횟수 
			int num1 = (int)(Math.random() * 6 + 1); // 첫번쨰 주사위 값 랜덤
			int num2 = (int)(Math.random() * 6 + 1); // 두번쨰 주사위 값 랜덤
			System.out.println("("+num1+","+num2+")");
			if(num1 + num2 == 10) {
				break; // 두 주사위 값이 10되면 반복 멈춤
			}
		}
		System.out.println("주사위를 던진 횟수 : " +count);
	}

}

 

문제2) 1 ~ 1000 사이의 숫자 중 3을 포함하고 있는 숫자를 출력

public class Exam {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(int i = 1; i<=1000; i++) {
			String num = String.valueOf(i); //정수 i를 문자열로 변환
			if(num.indexOf("3") >= 0) { //indexOf() 특정 문자나 문자열이 앞에서부터 처음 발견되는 인덱스를 반환
				System.out.println(i + " : 3 포함");
			}
	    }
    }
}

'Java' 카테고리의 다른 글

배열  (0) 2021.01.07
참조타입  (0) 2021.01.06
반복문 문제  (0) 2021.01.05
반복문  (0) 2021.01.05
가위바위보 게임(조건문 이용)  (0) 2021.01.05

+ Recent posts