Работа с методами для безопасной игры - PullRequest
0 голосов
/ 03 мая 2018

Я просто занят изучением Java, и моя задача состоит в создании безопасной игры. Мне нужно сделать эту игру с классами и методами. Но я дошел до точки и не могу идти дальше. Ниже я делюсь своим кодом и моими вопросами. Если бы вы могли взглянуть, я буду очень признателен.

import java.util.Random; import java.util.Scanner;

публичный класс Main {

public static void main(String[] args) {
    entrance();
    playGame();
    quitGame();
}

 private static void entrance() {
    System.out.println("Welcome to the SafeCracker!\nI need your help to open the safe box." +
            "\nThe code is with 3 digits and we need to find it out as quick as possible.\nLet's write your guess!");
}

 private static int playGame() {
    int[] safeCode = {takeRandomSafeCode(), takeRandomSafeCode(), takeRandomSafeCode()};
    int guess = takeGuess();

    //Below I need to use a for each loop but I don't get the logic of it. I stuck here. I need to check every numbers one by one but how?  

    for (int safeDigit : safeCode) {
        if (safeDigit == guess) {
            System.out.println("Your number is correct");

        }
    }
    return playGame(); // with this return type I also have a problem. 

Если я вернусь к этому методу, он продолжит играть снова и снова. Но я также не знаю, какой тип возврата мне нужно дать. }

private static int takeGuess() {
    Scanner keyboard = new Scanner(System.in);
    int userGuess = keyboard.nextInt();
    return userGuess;
}

private static int takeRandomSafeCode() {
    Random random = new Random();
    int result = random.nextInt(10);
    return result;
}

private static int quitGame() {
    System.out.println("Do you want to play again?\nPress 1 for play again\nPress 2 for quit the game!");
    Scanner key = new Scanner(System.in);
    int userWannaPlay = key.nextInt();

    if(userWannaPlay == 1) {
        System.out.println(playGame());
    } else if (userWannaPlay == 2) {
        System.out.println(quitGame());
    } else {
        System.out.println("You entered an invalid number. If you want to play again or quit, you need to click 1 or 2!");
    }
return userWannaPlay; //And also quitGame method. I want to ask the users that if they want to play or not and according to answer I would like to run "playGame" method again or quit game.
}

Ответы [ 2 ]

0 голосов
/ 03 мая 2018

Если я верну этот метод, он продолжит играть снова и снова. Но я не знаю также, какой тип возврата мне нужно дать.

Ваш playGame*( метод вызывает себя рекурсивно в последней строке return playGame(). Я полагаю, вы сделали это, чтобы вообще что-нибудь вернуть Если вы думаете о своей проблеме, вы можете прийти к выводу, что вам вообще не нужно ничего возвращать (поскольку вы не знаете, что с ней делать). В этом случае вы можете ничего не возвращать void, как вы делали в main методе.

А также метод quitGame. Я хочу спросить пользователей, что если они хотят играть или нет, и в соответствии с ответом я хотел бы запустить "playGame" метод снова или выйдите из игры

Вы должны думать о том, что вы хотите. Вы хотите вызывать метод снова и снова в зависимости от условия. Для этого вы можете использовать цикл или рекурсию. Например, вы можете немного изменить свой метод main и добавить цикл do-while.

public static void main(String[] args) {
    entrance();
    int condition;
    do {
        playGame();
        condition = quitGame();
    } while (condition == 1);

Не забудьте изменить метод quitGame, потому что там вы пытаетесь рекурсивно решить свою проблему (удалите предложение if). Если вы хотите сделать это рекурсивно, игнорируйте вышеприведенное и посмотрите на этот фрагмент:

private static int quitGame() {
    System.out.println("Do you want to play again?\nPress 1 for play again\nPress 2 for quit the game!");
    Scanner key = new Scanner(System.in);
    int userWannaPlay = key.nextInt();

    if(userWannaPlay == 1) {
        playGame(); // you dont need a println here
    } else if (userWannaPlay == 2) {
       // you dont need to anything here
       System.out.println("Quitting...");
    } else {
        System.out.println("You entered an invalid number. If you want to play again or quit, you need to click 1 or 2!");
       // call quitGame again to ask for the choice again
       quitGame();
    }
return userWannaPlay; // if you do it like this, this return is also unnecessary and you could use a void method without returning anything
}
0 голосов
/ 03 мая 2018

Попробуйте использовать цикл для вашей игры.

Вы можете установить переменную quitGame из метода playGame или создать новый метод для решения пользователя.

public static void main(String [] args){

   entrance();
   do{
      playGame();

   }while(!quitGame)

}

public void playGame(){
   //Your code is here
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...