2016-09-21 3 views
0

Я пытаюсь сделать программу для карандашей-ножниц, которая является лучшей из двух из трех, где компьютер случайным образом катит 0-2, и каждый из них присваивается камню, бумаге или ножницам, а затем он сравнивает userInput и подсчитывает выигрыш для компьютера или игрока, а затем добавляет его.Введенная строка также назначается целому числу?

НО, я не могу понять, как сделать так, чтобы, если бы пользователь вводил «ножницы», программа могла бы знать, что ему также присвоено значение 2 (для сравнения).

public static void main(String[] args) { 
    Random r = new Random(); 
    int gameCount = 0; 
    int computerWins = 0; 
    int playerWins = 0; 
    int rock = 0; 
    int paper = 1; 
    int scissors = 2; 
    int playerChoice; 
    int computerChoice = r.nextInt(3); 

    System.out.println("Welcome to Rock Paper Scissors! Best 2 out of 3!"); 

    while (gameCount >= 0 && gameCount < 3) 
    { 
     System.out.println("Enter \"Rock\", \"Paper\", or \"Scissors\""); 
     break; 
    } 
     playerChoice = userInput.nextInt() 

     //If player enters anything besides rock, paper, or scissors 
     if (playerChoice < 0 || playerChoice >= 3) { 
      System.out.println("That wasn't an option"); 
      computerWins++; 
      gameCount++; 

      //The game goes on, and the winners are added up! 
     } else if (playerChoice == 0 && computerChoice == 1) { 
      computerWins++; 
      gameCount++; 
      System.out.println("Rock v Paper! Computer Wins!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } else if (playerChoice == 1 && computerChoice == 0) { 
      playerWins++; 
      gameCount++; 
      System.out.println("Paper v Rock! Player Wins!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } else if (playerChoice == 1 && computerChoice == 2) { 
      computerWins++; 
      gameCount++; 
      System.out.println("Paper v Scissors! Computer Wins!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } else if (playerChoice == 2 && computerChoice == 1) { 
      playerWins++; 
      gameCount++; 
      System.out.println("Scissors v Paper! Player Wins!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } else if (playerChoice == 2 && computerChoice == 0) { 
      computerWins++; 
      gameCount++; 
      System.out.println("Scissors v Rock! Computer Wins!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } else if (playerChoice == 0 && computerChoice == 2) { 
      playerWins++; 
      gameCount++; 
      System.out.println("Rock v Scissors! Player Wins!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } else if (playerChoice == 0 && computerChoice == 0) { 
      gameCount++; 
      System.out.println("Rock v Rock! Tie!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } else if (playerChoice == 1 && computerChoice == 1) { 
      gameCount++; 
      System.out.println("Paper v Paper! Tie!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } else if (playerChoice == 2 && computerChoice == 2) { 
      gameCount++; 
      System.out.println("Paper v Paper! Tie!\n" + 
        "Player has won " + playerWins + " times and the computer " + 
        "has won " + computerWins + " times"); 
     } 

     //Check if game count reaches max games then chooses a winner 
     if (gameCount == 3 && computerWins > playerWins) { 
      System.out.println("The Computer Wins!"); 
     } else if (gameCount == 3 && computerWins < playerWins) { 
      System.out.println("The Player Wins!"); 
     } else if (gameCount == 3 && computerWins == playerWins) { 
      System.out.println("The game is a tie!"); 
     } 
    } 
} 
+0

Взгляните на перечисления, они решают вашу проблему –

ответ

0

Так вместо playerChoice = userInput.nextInt(); попробовать это:

Scanner sc = new Scanner(System.in); 
String input = sc.nextLine(); 
try { 
    playerChoice = Integer.parseInt(input); 
} catch (NumberFormatException e) { 
    if (input.equalsIgnoreCase("rock")) { 
     playerChoice = rock; 
    } else if (input.equalsIgnoreCase("paper")) { 
     playerChoice = paper; 
    } else if (input.equalsIgnoreCase("scissors")) { 
     playerChoice = scissors; 
    } else { 
     // if input is invalid 
     playerChoice = -1; 
    } 
} 

Поскольку вы используете userInput.nextInt() и playerChoice является INT и может содержать только Интс, вы должны проанализировать ввод вашего пользователя. В этом случае Integer.parseInt(input) попытается найти int в пользовательском вводе. Если он не может, он вернет исключение; поэтому есть блок try-catch. Если это не int, он будет искать каждую строку и назначить соответствующее значение int playerChoice или -1, если вход недействителен. Затем остальная часть вашего кода должна иметь возможность надлежащим образом обрабатывать playerChoice после этого.

+0

Спасибо! Я сделаю так! –

Смежные вопросы