-
주사위 A와 B를 동시에 100회 던진 결과의 합을 토대로, 출력 예와 같은 결과를 만드시오Back end/Java 객체지향 2023. 11. 22. 01:12
// 자바 API를 불러옴
import java.lang.Math;
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
// 배열 생성
int[] counts = new int [13]; // 0 ~ 12
// 변수 생성 및 주사위 던지기
for(int i = 0; i < 100; i++){
int a = DieA.roll();
int b = DieB.roll();
counts[a + b]++; // 해당 배열 번호에 추가
}
// 결과 출력
for (int row =2; row < counts.length; row++){ // 2 ~ 12
System.out.prinln("%d =>", row);
// #을 출력
for (int col = 0; col < counts[row]; col++){ // row가 5번이면 5번 반복 하는거
System.out.prinln ("#");
}
System.out.println();
}
}
}
class DieA {
// 1 부터 6사이 정수를 반환 [참고] https://cloudstudying.kr/challenges/348
public static int roll() {
double r = Math.random() * 6; // 0.0 <= r < 6.0
int randInt = (int) r; // 0, 1, 2, ..., 5
return randInt + 1; // 1, 2, 3, ..., 6
}
}
class DieB {
public static int roll() {
// 1 부터 6사이 정수를 반환 [참고] https://cloudstudying.kr/challenges/404
Random rand = new Random();
int randInt = rand.nextInt(6); // (0 ~ 5)
return randInt + 1;
}
}출력
2 =>####
3 =>#####
4 =>##############
5 =>#########
6 =>################
7 =>##############
8 =>########
9 =>############
10 =>#########
11 =>######
12 =>###출저: 홍팍 (https://www.youtube.com/@hongpark)
이 블로그 기록은 개인 공부용 기록입니다.
'Back end > Java 객체지향' 카테고리의 다른 글
업 캐스팅? (0) 2023.11.22 ArrayList (0) 2023.11.22 접근 제한자 (Access Modifer) (0) 2023.11.21 Getter & Setter 문제 (0) 2023.11.21 인스턴스, 클래스 메소드 문제 (0) 2023.11.21