이 코드를 가독성좋게 만드는 과제이다.
public class Main {
public static void main(String[] args) {
int repeatNum = InputNum();
diceCount(repeatNum);
}
private static void diceCount(int repeatNum) {
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < repeatNum; i++){
int dice = (int) (Math.random() * 6) + 1;
Integer result = map.put(dice, map.getOrDefault(dice, 0) + 1);
}
for(int key : map.keySet()){
Integer value = map.get(key);
System.out.println(key + "은 " + value+"번 나왔습니다.");
}
}
public static int InputNum(){
System.out.print("숫자를 입력하세요 : ");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
return num;
}
}
먼저 inputNum 메서드로 주사위를 몇번 반복할것인지 얻어오고
diceCount() 메서드는 주사위번호가 몇번 나온지 알려준다.
diceCount 메서드에서는 주사위숫자와 주사위번호가 몇번 나왔는지
저장하기위해서 hashMap을 사용하였다
먼저 for문을통해서 repeatNum 만큼 반복을해주고
map에 저장을 하는데
map.getOrDefault()는 해당 key의 value가 없을때 value=0을 기본설정해준다
그리고 +1은 해당 key가 들어올때 value를 1씩 더해준다
마지막으로 map.keySet()을해서 map에 저장된 모든key값들을 불러오고
map.get(key)를 해서 value도 얻어오고
print문으로 key와 value를 출력해주면된다.