Created
October 8, 2022 16:59
-
-
Save misterhay/123767bb47821e57bd94dce7db167430 to your computer and use it in GitHub Desktop.
Basic One-Player Rock, Paper, Scissors in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.util.Arrays; | |
public class RockPaperScissors | |
{ | |
public static void RockPaperScissors() | |
{ | |
String[] possibleChoices = {"rock", "paper", "scissors"}; | |
Scanner userInput = new Scanner(System.in); // create a Scanner for getting user input | |
String playerChoice = ""; // declare an empty variable that we'll fill with the user input | |
while (!Arrays.asList(possibleChoices).contains(playerChoice)) { // keep asking if user input is not correct | |
System.out.print("Type rock, paper, or scissors: "); | |
playerChoice = userInput.nextLine(); | |
} | |
// we now have a playerChoice that is from possibleChoices | |
System.out.print("You selected "); | |
System.out.println(playerChoice); | |
// the computer choses a random value from possibleChoices | |
int randomChoice = (int)(Math.random()*3); | |
String computerChoice = possibleChoices[randomChoice]; | |
System.out.print("The computer selected "); | |
System.out.println(computerChoice); | |
// check who wins, default to the computer winning | |
String winner = "The computer wins."; | |
if (playerChoice.equals(computerChoice)) { | |
winner = "It is a tie."; | |
} else { | |
if (playerChoice.equals("rock") && computerChoice.equals("scissors")) { | |
winner = "You win."; | |
} else if (playerChoice.equals("paper") && computerChoice.equals("rock")) { | |
winner = "You win."; | |
} else if (playerChoice.equals("scissors") && computerChoice.equals("paper")) { | |
winner = "You win."; | |
} | |
} | |
System.out.println(winner); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment