티스토리 뷰
728x90
// 1.Class Declaration;
// The code defines a class named 'RandomGame', which contains methods and variables
// to implement the number guessing game.
public class RandomGame {
// 2. Instance Variables;
// 'answer' This is an instance variable that will store the correct answer to the guessing game. It's initially set to -1.
// 사용자가 입력하는 변수는 반드시 전역변수여야 한다.
// 'sc' This is an instance of the 'Scanner' class, used for reading user input from the console.
int answer = -1;
Scanner sc = new Scanner(System.in);
// 3. 'getRandom' Method;
// This method generates a random number between 0 and 9 using the 'Random' class and stores it in the 'answer' variable.
public void getRandom() {
Random r = new Random(); //리턴타입 없이도, 전역변수라면 어떠한 메소드에서도 재정의할 수 있다.
answer = r.nextInt(10);
}
// 4. 'getNum' Method;
// This method reads an integer input from the user using the 'Scanner' and returns the user's input.
public int getNum() {
int user = 0;
user = sc.nextInt();
return user;
}
// 5. 'account(int user)' Method;
// This method takes the user's input as a parameter and compares it with the 'answer'.
// It returns a hint as a String, indicating whether the user's guess is correct or if they should guess higher or lower.
public String account(int user) {
String hint = null;
if(answer == user) {
hint ="정답입니다.";
}else if(answer > user) { //사용자가 입력한 값이 정답보다 작으면 높여라를 반환.
hint ="높여라.";
}else if(answer < user) { //사용자가 입력한 값이 정답보다 크면 낮춰라 반환.
hint ="낮춰라.";
}
return hint;
}
// 6. messagePrint(int user) Method;
// This method prints the hint returned by the 'account' method based on the user's input.
public void messagePrint(int user) { //user = 5 복사
System.out.println(account(user)); //24 -> 5를 쥐고간다. -> 높여라 출력
}
// 7. main Method;
// main method is the entry point of the program.
// It creates an instance of the 'RandomGame' class, generates a random answer,
// and then asks the user to input a number.
public static void main(String[] args) {
RandomGame rg = new RandomGame();
rg.getRandom();
System.out.println("숫자 입력: ");
for(int i=5; i > 0; i--) {
int user = rg.getNum();
rg.messagePrint(user);
}
}
}
'Programming Language > JAVA' 카테고리의 다른 글
[Java] next(), nextLine() (0) | 2023.10.03 |
---|---|
[Java] GUI 기초, Swing과 AWT (0) | 2023.10.02 |
[Java] 배열(Array) & 배열 리스트 (ArrayList) (0) | 2023.09.30 |
[Java] Get, Set (0) | 2023.09.27 |
[자바/실습] (0) | 2023.09.25 |