초급과정/java

[Java] 주사위 2개를 1000번 던져서 두 개의 합(2~12) 갯수를 카운트해서 출력하기

whalerice 2023. 10. 25. 21:03
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class HistoGram {
	/*
	 * 요구사항.
	 * 
	 * 주사위 2개를 던져서 총 주사위 합을 
	 * 
	 * 1000번 시행 후 해당 값을 저장 할 것 (리스트 )
	 * 전체 히스토그램을 구해 볼 것 
	 * 주사위 눈은 1~6으로 구현되어 있음.
	 * 
	 */
	
	List<Integer> diceList = new ArrayList();
	 
	public static void main(String[] args) {
		HistoGram hg = new HistoGram();		
		for(int i=0; i<1000; i++) {
			int sum = hg.throwDice();
			hg.diceList.add(sum);
		}
		hg.print();		
	}
	
	public int throwDice() {
		//주사위 던지는걸 2번		
		int dice1 = (int)(Math.random()*6)+1;
		int dice2 = (int)(Math.random()*6)+1;
		
		return dice1+dice2;
	}
	
	public int getDiceNumCount(int num) {
		int count = 0;
		for (int i = 0; i<diceList.size(); i++) {
			if(diceList.get(i)==num) {
				count++;
			}
		}					
		return count;
	}
	
	public void print() {
		for(int i =2; i<=12; i++) {
			System.out.println("주사위 합"+i+"는  "+getDiceNumCount(i)+"번 나왔다.");
		}
	}
}