更好的算法?更好的阵列?

时间:2015-01-14 15:45:57

标签: java arrays algorithm random

这是我的代码:

/* 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语句中使用三个独立的条件吗?另外,我的数组中没有“零”字符串,如何仅使用数字1,2和3检查数组?

1 个答案:

答案 0 :(得分:1)

只需使用

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))