Метод возвращает правильное значение, но если цикл не действует соответственно - PullRequest
0 голосов
/ 23 ноября 2018

Я выписал весь код для задания для моего класса программирования.Задание требует, чтобы мы создали программу, которая позволяет пользователю играть в камень ножницами против компьютера.Мы должны иметь индивидуальные методы, чтобы получить выбор компьютера, выбор пользователя, проверить, является ли выбор пользователя действительным, а также определить победителя матча.Если матч не заканчивается ничьей, мы должны напечатать, почему матч был выигран, например.«Ножницами режет бумагу» и печатай, кто победит.Все работает правильно, за исключением случаев, когда пользователь выигрывает, он никогда не считается и не объявляется.Например, вместо печати:

Выбор компьютера был рок.Выбор пользователя был бумажным.Бумажные обложки Rock.Пользователь выигрывает!

он печатает:

Выбор компьютера был потрясающим.Выбор пользователя был бумажным.Бумага покрывает камень.

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

public class FinalRockPaperScissors {

//Computer's Choice
public static int computersChoice (int options) {
    Random randGen = new Random();
    int computerValue = randGen.nextInt(options)+1;
    System.out.println(computerValue); //FOR TESTING ONLY
    return computerValue;
}

//Player's Choice
public static int usersChoice () {
    Scanner scnr = new Scanner(System.in);
    System.out.print("Enter 1 for rock, 2 for paper, or 3 for scissors: ");
    int userValue = scnr.nextInt();

    if (isValid(userValue) == true) {
        return userValue;
    }

    else {
        userValue = 0;
        return userValue;
    }


}

//Check for valid user input
public static boolean isValid (int userInput){
    if (userInput == 1 || userInput == 2 || userInput == 3) {
        return true;
    }

    else {
        return false;
    }
}

//Checking winner
public static char determineWinner () {
    char win;
    int computerValue = computersChoice(3);
    int userValue = usersChoice();

    //print computer choices
    if (computerValue == 1) {
        System.out.println("The computer's choice was rock.");
    }

    else if (computerValue == 2) {
        System.out.println("The computer's choice was paper.");
    }

    else if (computerValue == 3){
        System.out.println("The computer's choice was scissors.");
    }

    //print user choices
            if (userValue == 1) {
                System.out.println("The user's choice was rock.");
            }

            else if (userValue == 2) {
                System.out.println("The user's choice was paper.");
            }

            else if (userValue == 3){
                System.out.println("The user's choice was scissors.");
            }


    //check who won
    if (computerValue == 1) { //rock vs
        if (userValue == 2) {           //paper
            System.out.println("Paper wraps Rock.");
            return win = 'b'; 
        }

        else if (userValue == 3) {      //scissors
            System.out.println("Rock smashes Scissors.");
            return win = 'a'; 
        }

        else if (userValue == 1){                           //rock
            return win = 'c'; 
        }

        else {
            System.out.println("The user chose an invalid number. This round will be ignored.");
            return win = 'd';
        }

    }

    else if (computerValue == 2) { //paper vs
        if (userValue == 2) {           //paper
            return win = 'c'; 
        }

        else if (userValue == 3) {      //scissors
            System.out.println("Scissors cuts Paper.");
            return win = 'b'; 
        }

        else if (userValue == 1){                           //rock
            System.out.println("Paper wraps Rock.");
            return win = 'a'; 
        }

        else {
            System.out.println("The user chose an invalid number. This round will be ignored.");
            return win = 'd';
        }

    }

    else { //scissors vs
        if (userValue == 2) { //paper
            System.out.println("Scissors cuts Paper.");
            return win = 'a';
        }

        else if (userValue == 3) { //scissors
            return win = 'c';
        }

        else if (userValue == 1){ //rock
            System.out.println("Rock smashes Scissors.");
            return win = 'b';
        }

        else {
            System.out.println("The user chose an invalid number. This round will be ignored.");
            return win = 'd';
        }

    }

}

public static void main(String[] args) {
    int userWins = 0;
    int computerWins = 0;
    int ties = 0;
    int error = 0;

    //for (int i = 0; i < 1; i++) { //5 for testing purposes
        if (determineWinner() == 'a') {
            System.out.println("The computer wins!");
            System.out.println("");
            computerWins++;
        }

        else if (determineWinner() == 'b') {
            System.out.println("The user wins!");
            System.out.println("");
            userWins++;
        }

        else if (determineWinner() == 'c'){
            System.out.println("The game is tied!");
            System.out.println("");
            ties++;
        }

        else {
            error++;
        }
    //}

    System.out.println("The number of ties is " + ties);
    System.out.println("The number of user wins is " + userWins);
    System.out.println("The number of computer wins is " + computerWins);

    //output final winner
    if (computerWins > userWins) {
        System.out.println("Computer is the winner.");
    }

    else if (userWins > computerWins) {
        System.out.println("User is the winner.");
    }

    else {
        if (userWins == computerWins) {
            System.out.println("User is the winner.");
        }
        else if (computerWins == ties) {
            System.out.println("Computer is the winner.");
        }
    }


}

}

После некоторых испытаний я обнаружил, что проблема может быть в моем методе userchoice().Если я отключу этот метод и дам пользователю заданное значение, все будет работать как надо.Проблема в том, что я не знаю, почему это не работает, и в результате я не могу это исправить.

Ответы [ 2 ]

0 голосов
/ 23 ноября 2018

Я думаю, что вы новичок в Java, а также давайте начнем показывать вам вашу ошибку в этом коде, вы неоднократно вызывали determineWinner(), что не должно быть так, потому что вы повторяете игру четыре раза, чтобы определитьрезультат один раз, поэтому вы должны вызвать его один раз, получить возвращаемое значение и проверить значение, например: -

char result = determineWinner(); //Play the game and get the result

// use it in conditions

if (result == 'a') {  
    System.out.println("The computer wins!");
    System.out.println("");
    computerWins++;
}

else if (result == 'b') {
    System.out.println("The user wins!");
    System.out.println("");
    userWins++;
}

else if (result == 'c'){
    System.out.println("The game is tied!");
    System.out.println("");
    ties++;
}

else {
    error++;
}
0 голосов
/ 23 ноября 2018

В вашей функции main Вы звоните determineWinner() каждый раз, когда проверяете свое условие if.Правильным способом было бы сохранить возвращаемое значение в переменной, а затем проверить, является ли эта переменная 'a', 'b' или 'c'.Например:

char result = determineWinner();
if (result == 'a') {
    System.out.println("The computer wins!");
    System.out.println("");
    computerWins++;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...