Ok, so I have programmed a simple rock paper scissors game using user input to play. The user types their choice, a random function chooses the computers go and then a result is produced. After this the program is terminated because it has finished. I want to use a while loop so that when the game is finished, it starts again, and then the program will stop if the user types in exit or quit, which can easily be done by just saying something like while playerGo != exit, play the game blah blah. However, I cannot get this to work, can someone help me please, I’m a Java noob 🙂
import java.util.Scanner;
public class RockPaperScissors{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int compGoInt;
String compGo;
String playerGo;
System.out.println("You can type 'Exit' to quit the game at any time.");
System.out.print("Please enter your choice. Rock, Paper or Scissors: ");
playerGo = input.nextLine();
compGoInt = (int) (Math.random() * 3);
switch (compGoInt){
case 0:
compGo = "Rock";
break;
case 1:
compGo = "Paper";
break;
case 2:
compGo = "Scissors";
break;
default:
compGo = "Error";
System.out.println("Error.");
break;
}
if (playerGo.equals(compGo)){
System.out.println("Computer chooses "+compGo);
System.out.println("It's a draw!");
}
else if ((playerGo.equalsIgnoreCase("Rock") && compGo.equalsIgnoreCase("Scissors")) ||
(playerGo.equalsIgnoreCase("Paper") && compGo.equalsIgnoreCase("Rock")) ||
(playerGo.equalsIgnoreCase("Scissors") && compGo.equalsIgnoreCase("Paper"))){
System.out.println("Computer chooses "+compGo);
System.out.println("Player Wins!");
}
else if ((compGo.equalsIgnoreCase("Rock") && playerGo.equalsIgnoreCase("Scissors")) ||
(compGo.equalsIgnoreCase("Paper") && playerGo.equalsIgnoreCase("Rock")) ||
(compGo.equalsIgnoreCase("Scissors") && playerGo.equalsIgnoreCase("Paper"))){
System.out.println("Computer chooses "+compGo);
System.out.println("Computer Wins!");
}
else{
System.out.println("Something has gone wrong!");
System.out.println("Player chose "+playerGo);
System.out.println("Computer chose "+compGo);
}
}
}
Simply put:
Though, if I may say so, you should have the user choose a number, since any letter input is prone to errors.
For clarification purposes: