2015-06-12 4 views
0

Хорошо, у меня есть назначение класса, чтобы создать 3 предопределенных метода для программы скалы, бумаги, ножниц, написанной учителем. Тем не менее, когда я запускаю программу, он несколько раз подряд запускает методы. Я просмотрел код несколько раз и не могу понять проблему.Имея проблемы с методами

Ниже учитель предоставляется часть программы:

public class Game 
{ 

    public static void main (String[] args) 
    { 
     Scanner in = new Scanner (System.in); 
     RockPaperScissors rps = new RockPaperScissors(); //***Your class 

     int numGames = 0; 
     String userChoice = ""; 
     String cpuChoice = ""; 
     String winner = ""; 
     int userWins = 0; 
     int cpuWins = 0; 


     System.out.println("Welcome to Rock, Paper, Scissors!\n"); 

     //Get odd number of games 
     System.out.println("How many rounds would you like to play?"); 
     numGames = in.nextInt(); 

     while (numGames % 2 == 0) //Even number 
     { 
      System.out.println("Sorry, number of games must be odd. Please try again:"); 
      numGames = in.nextInt(); 
     } 

     //Flush the buffer 
     in.nextLine(); 

     //Play the game for the number of rounds the user entered 
     for (int i = 1; i <= numGames; i++) 
     { 
      //Get the user and computer choices 
      userChoice = rps.getUserChoice(); //***Your method 
      cpuChoice = rps.getCPUChoice(); //***Your method 


      System.out.println("Computer chooses " + cpuChoice); 

      //Pick winner 
      winner = rps.pickWinner(userChoice, cpuChoice); //***Your method 


      if (winner.equalsIgnoreCase("Tie")) 
      { 
       System.out.println("It's a tie! Play again."); 
       numGames++; 
      } 
      else 
      { 
       if (winner.equalsIgnoreCase("User")) 
       { 
        userWins++; 
       } 
       else if (winner.equalsIgnoreCase("Computer")) 
       { 
        cpuWins++; 
       } 
       else 
       { 
        System.out.println("Error in picking winner"); 
       } 

       System.out.println(winner + " wins!"); 
      } 

     } //end for 

     //Print results 
     System.out.println("\nUser wins: " + userWins); 
     System.out.println("Computer wins: " + cpuWins); 

     if (userWins > cpuWins) 
     { 
      System.out.println("\nThe user won!"); 
     } 
     if (cpuWins > userWins) 
     { 
      System.out.println("The computer won!"); 
     } 

     //Close game 
     System.out.println("\nThank you for playing!"); 

    } //end main 

} //end class 

И вот мой код, который я предполагаю, где эта проблема исходит от:

public class RockPaperScissors { 


    public String getUserChoice() { 
     Scanner sc = new Scanner (System.in); 
     System.out.println("Enter your choice:"); 
     String userInput = sc.nextLine(); 
     boolean end = true; 
     while (end == true){ 

      //Checks for valid user responses 
      if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){ 
       end = false; 
      } 
      else { 
       System.out.println("Invalid response. Please enter rock paper or scissors:"); 
       userInput = sc.next(); 
      } 
     } 

     return userInput; 
    }// end getUsechoice 

    public String getCPUChoice() { 

     String computerChoice = " "; 
     Random rand = new Random(); 
     int randomNum = rand.nextInt(3) + 1; 
     if (randomNum == 1){ 
      computerChoice = "rock"; 
     } 
     else if (randomNum == 2){ 
      computerChoice = "paper"; 
     } 
     else if (randomNum == 3){ 
      computerChoice = "scissors"; 
     } 


     return computerChoice; 
    } 

    public String pickWinner(String userChoice, String cpuChoice) { 
     String result = " "; 
     if (getUserChoice().equalsIgnoreCase("rock")) { 
      if (getCPUChoice().equalsIgnoreCase("rock")){ 
       result = "tie"; 
      } 
      else if (getCPUChoice().equalsIgnoreCase("paper")){ 
       result = "Computer"; 
      } 
      else if (getCPUChoice().equalsIgnoreCase("scissors")){ 
       result = "User"; 
      }  
     } 
     else if (getUserChoice().equalsIgnoreCase("paper")){ 
      if (getCPUChoice().equalsIgnoreCase("paper")){ 
       result = "tie"; 
      } 
      else if (getCPUChoice().equalsIgnoreCase("rock")){ 
       result = "User"; 
      } 
      else if (getCPUChoice().equalsIgnoreCase("scissors")){ 
       result = "Computer"; 
      } 
     } 
     else if (getUserChoice().equalsIgnoreCase("Scissors")){ 
      if (getCPUChoice().equalsIgnoreCase("scissors")){ 
       result = "tie"; 
      } 
      else if (getCPUChoice().equalsIgnoreCase("rock")){ 
       result = "Computer"; 
      } 
      else if (getCPUChoice().equalsIgnoreCase("Paper")){ 
       result = "User"; 
      } 
     } 
     return result; 



    }//end pickWinner 

}//end rockPaperScissors 

Вот бы образец сессия программы:

Добро пожаловать в Rock, Paper, Scissors!

Сколько раундов вы хотели бы сыграть? 1 Введите свой выбор: rock Компьютер выбирает бумагу Введите свой выбор: rock Введите ваш выбор: rock Компьютер побеждает!

Побед: 0 Выигрывает компьютер: 1 Компьютер выиграл!

Благодарим за участие!

Здесь я задаюсь вопросом, почему он продолжает запрашивать ввод пользователя несколько раз. Кроме того, он запускает и другие методы, поэтому компьютер выигрывает, несмотря на сбор бумаги против камня.

Хорошо добавил в финальных изменений в моей программе, и теперь он отлично работает:

public String pickWinner(String userChoice, String cpuChoice) { 
     String result = " "; 


     if (userChoice.equalsIgnoreCase("rock")) { 
      if (cpuChoice.equalsIgnoreCase("rock")){ 
       result = "tie"; 
      } 
      else if (cpuChoice.equalsIgnoreCase("paper")){ 
       result = "Computer"; 
      } 
      else if (cpuChoice.equalsIgnoreCase("scissors")){ 
       result = "User"; 
      }  
     } 
     else if (userChoice.equalsIgnoreCase("paper")){ 
      if (cpuChoice.equalsIgnoreCase("paper")){ 
       result = "tie"; 
      } 
      else if (cpuChoice.equalsIgnoreCase("rock")){ 
       result = "User"; 
      } 
      else if (cpuChoice.equalsIgnoreCase("scissors")){ 
       result = "Computer"; 
      } 
     } 
     else if (userChoice.equalsIgnoreCase("Scissors")){ 
      if (cpuChoice.equalsIgnoreCase("scissors")){ 
       result = "tie"; 
      } 
      else if (cpuChoice.equalsIgnoreCase("rock")){ 
       result = "Computer"; 
      } 
      else if (cpuChoice.equalsIgnoreCase("Paper")){ 
       result = "User"; 
      } 
     } 
     return result; 



    }//end pickWinner 

Проблема, кажется, что, когда я позвонил в getCPUChoice или getUserChoice было бы повторно запустить программу, а затем изменить окончательные ответы ,

+1

Просто небольшая оптимизация: выберите выбор центрального процессора из 'public static final String [] sChoices = {" rock "," paper "," scissors "}'. Тогда вы можете получить случайный (назовем его pickNr) в {0; 2} и получить выбор только с помощью 'return sChoices [pickNr];' И я сделаю случайный объект полем класса, так что вы не сделаете новый в каждом вызове computerChoice. Затем computerChoice является 1-лайнером. – Fildor

+0

Что меня беспокоит, так это то, что ответ не очень полезен для будущих читателей.«Этот вопрос был вызван проблемой, которая больше не может быть воспроизведена или простой типографской ошибкой». Поэтому его нужно хотя бы отредактировать. –

ответ

1

Вы вызываете getUserChoice() в методе pickWinner. Он должен быть параметром метода userChoice, который вы должны проверять.

public String pickWinner(String userChoice, String cpuChoice) { 
String result = " "; 
if (userChoice.equalsIgnoreCase("rock")) { 
    if (cpuChoice.equalsIgnoreCase("rock")){ 
     result = "tie"; 
    } 
    else if (cpuChoice.equalsIgnoreCase("paper")){ 
     result = "Computer"; 
    } 
    else if (cpuChoice.equalsIgnoreCase("scissors")){ 
     result = "User"; 
    }  
} 
else if (userChoice.equalsIgnoreCase("paper")){ 
    if (cpuChoice.equalsIgnoreCase("paper")){ 
     result = "tie"; 
    } 
    else if (cpuChoice.equalsIgnoreCase("rock")){ 
     result = "User"; 
    } 
    else if (cpuChoice.equalsIgnoreCase("scissors")){ 
     result = "Computer"; 
    } 
} 
else if (userChoice.equalsIgnoreCase("Scissors")){ 
    if (cpuChoice.equalsIgnoreCase("scissors")){ 
     result = "tie"; 
    } 
    else if (cpuChoice.equalsIgnoreCase("rock")){ 
     result = "Computer"; 
    } 
    else if (cpuChoice.equalsIgnoreCase("Paper")){ 
     result = "User"; 
    } 
} 
return result; 
+0

У тебя острый глаз.) –

+0

Также ваш цикл for, хотя работает стандарт, должен иметь переменную i начинаться с 0, поэтому для for (int i = 0; i slarge

+0

А, это, похоже, проблема. – Trevor

0

попробуйте изменить это в еще части

userInput = sc.next(); 

к этому

userInput = sc.nextLine(); 

Так будет перейти к следующей строке

Таким образом, результирующий код будет

while (end == true){ 

    //Checks for valid user responses 
    if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){ 
     end = false; 
    } 
    else { 
     System.out.println("Invalid response. Please enter rock paper or scissors:"); 
     userInput = sc.nextLine(); 
    } 
} 
+0

Эта часть кода работает как минимум. Он предназначен для того, чтобы поймать ответы, которые не являются камнем, бумагой или ножницами. – Trevor

1

Вы должны как k для ввода пользователем в каждом цикле, а не только один раз.

public class RockPaperScissors { 


    public String getUserChoice() { 
     Scanner sc = new Scanner (System.in); 
     System.out.println("Enter your choice:"); 
     //not here 
     String userInput; 
     while (true){ 
      //this is the right place 
      userInput = sc.nextLine(); 
      //Checks for valid user responses 
      if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){ 
       break; 
      } 
      else { 
       System.out.println("Invalid response. Please enter rock paper or scissors:"); 
      } 
     } 

     return userInput; 
    }// end getUsechoice 

//... 

}//end rockPaperScissors