[Java] 랜덤 주사위를 만들어 숫자 맞추기 게임

JTI·2022년 10월 18일
0

📌 Code list

목록 보기
19/55
post-thumbnail

💡 반복문 없는 코드

import java.util.Scanner;

class DiceGame {
	private int diceFace;
	private int userGuess;

	private int rollDice()	{
		return (int)(Math.random() * 6) + 1; // Math 함수
	}
	private int getUserInput() {
		System.out.println("예상값을 입력하시오: ");
		Scanner s = new Scanner(System.in);
		return s.nextInt();
	}
	private void checkUserGuess() {
		if( diceFace == userGuess ) {
			System.out.println("맞았습니다.");
		} else {
			System.out.println("틀렸습니다.");
		}
	}
	public void startPlaying() {	
		userGuess = getUserInput();
		diceFace = rollDice();
		checkUserGuess();
	}
}
public class DiceGameTest {
	public static void main(String[] args) {
		DiceGame game = new DiceGame();
		game.startPlaying();	
	}
}
[결과값]

예상값을 입력하시오: 
2
맞았습니다.

메서드간의 분리와 수정을 원활하게 하기 위해 startPlaying메서드 말고는 private으로 접근제한자를 두었다.

💡 반복문 있는 코드

import java.util.Scanner;

class Dice {
	private int diceEye;
	private int userPick;
	
	public int ramdomDice() {
		return (int)(Math.random() * 6) + 1;
	}
	public int userNum() {
		Scanner scan = new Scanner(System.in);
		System.out.println("1~6까지의 숫자를 입력해주세요: ");
		return scan.nextInt();
	} 
	public void checkUserNum() {
		diceEye = ramdomDice();
		do {
			userPick = userNum();
			if(diceEye > userPick) {
				System.out.println("큰 수를 노려봐요!");
			} else if(diceEye < userPick) {
				System.out.println("작은 수를 노려봐요!");
			} else {
				System.out.println("정답입니다!");
			}
		} while(diceEye != userPick);
	}
}


public class DiceGame {

	public static void main(String[] args) {
		Dice d = new Dice();
		d.checkUserNum();
	}

}

Math함수에 대해서 자세한 내용은 요기 !
https://velog.io/@jipark09/Java-%EB%9E%9C%EB%8D%A4Random%ED%95%A8%EC%88%98-%EC%83%9D%EC%84%B1-%EB%AA%85%EB%A0%B9

profile
Fill in my own colorful colors🎨

0개의 댓글