I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also “knowing” what beats what. The Java enum is perfect for this.
public enum Type{ ROCK, PAPER, SCISSOR; public static Type parseType(String value){ //if /else logic here to return either ROCK, PAPER or SCISSOR //if value is not either, you can return null } }
The parseType
method can return null
if the String is not a valid type. And you code can check if the value is null and if so, print “invalid try again” and loop back to re-read the Scanner.
Type person=null; while(person==null){ System.out.println("Enter your play: "); person= Type.parseType(scan.next()); if(person ==null){ System.out.println("invalid try again"); } }
Furthermore, your type enum can determine what beats what by having each Type
object know:
public enum Type{ //... //each type will implement this method differently public abstract boolean beats(Type other); }
each type will implement this method differently to see what beats what:
ROCK{ @Override public boolean beats(Type other){ return other == SCISSOR; } } ...
Then in your code
Type person, computer; if (person.equals(computer)) System.out.println("It's a tie!"); }else if(person.beats(computer)){ System.out.println(person+ " beats " + computer + "You win!!"); }else{ System.out.println(computer + " beats " + person+ "You lose!!"); }