这是我的代码:
/* Name: Steven Royster
* Date: Jan. 15, 2015
* Rock, Paper, Scissors Program
* This program simulates a game of rock, paper, scissors with the user until someone has one a total of five times.
*/
import java.util.Random;
import java.util.Scanner;
public class RPS {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Let's play rock, paper, scissors! First to five wins!");
String[] choice = { "zero" , "rock" , "paper" , "scissors" };
Random rander = new Random();
Scanner input = new Scanner(System.in);
int userScore = 0, compScore = 0,
userChoice, compChoice;
while (compScore < 5 && userScore < 5)
{
compChoice = rander.nextInt(3) + 1;
System.out.println("\nEnter: 1 for ROCK | 2 for PAPER | 3 for SCISSORS.");
userChoice = input.nextInt();
if (compChoice == userChoice) // tie
{
System.out.println("I chose " + choice[compChoice] + " too, so we tied!");
}
else if ( ( compChoice == 1 && userChoice == 3 ) //computer wins
|| ( compChoice == 2 && userChoice == 1 )
|| ( compChoice == 3 && userChoice == 2) )
{
System.out.println("I win! I chose " + choice[compChoice] + ". " +
choice[compChoice] + " beats " + choice[userChoice] + "." );
compScore += 1;
}
else //human wins
{
System.out.println("You win! I chose " + choice[compChoice] + ". " +
choice[userChoice] + " beats " + choice[compChoice] + ".");
userScore += 1;
}
}//end while
if (userScore == 5)
{
System.out.println("\nCongrats! You're the winner! You got "
+ userScore + " points. I only got " + compScore + " points." );
}
}//end main
}//end class
有没有更好的算法可以实现,而不是在else if语句中使用三个独立的条件?另外,与其在数组中使用“0”字符串,还不如只使用数字1、2和3检查数组?
最佳答案
只是使用
String[] choice = { "rock" , "paper" , "scissors" };
然后你就可以做
choice[userChoice]
,而不是choice[userChoice - 1]
。你不需要写信
if ( ( compChoice == 1 && userChoice == 3 )
|| ( compChoice == 2 && userChoice == 1 )
|| ( compChoice == 3 && userChoice == 2) )
因为它和
if (compChoice == 1 + (userChoice % 3))
关于java - 更好的算法?更好的数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27946917/