我建议制作石头、剪刀、布的物体。这些对象将具有与字符串之间进行转换的逻辑,并且还“知道”什么击败什么。 Java 枚举非常适合此目的。
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
方法可以返回null
如果 String 不是有效类型。您的代码可以检查该值是否为空,如果是,则打印“无效重试”并循环返回以重新读取扫描仪。
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");
}
}
此外,您的类型枚举可以通过让每个类型来确定什么击败什么Type
对象知道:
public enum Type{
//...
//each type will implement this method differently
public abstract boolean beats(Type other);
}
每种类型都会以不同的方式实现此方法,看看哪种方法更胜一筹:
ROCK{
@Override
public boolean beats(Type other){
return other == SCISSOR;
}
}
...
然后在你的代码中
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!!");
}