【问题标题】:Better Algorithm? Better Array?更好的算法?更好的阵列?
【发布时间】:2015-01-14 15:45:56
【问题描述】:

这是我的代码:

/* 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 来检查我的数组,而不是在我的数组中包含“零”字符串?

【问题讨论】:

标签: java arrays algorithm random


【解决方案1】:

随便用

String[] choice = { "rock" , "paper" , "scissors" };

那么你可以用choice[userChoice - 1]代替choice[userChoice]

你不需要写

if ( ( compChoice == 1 && userChoice == 3 )              
           || ( compChoice == 2 && userChoice == 1 ) 
           || ( compChoice == 3 && userChoice == 2) )

因为是一样的

if (compChoice == 1 + (userChoice % 3))

【讨论】:

  • 太棒了!非常有帮助,我很感激。
  • @S.Royster 不用担心。我很高兴能帮上忙。
猜你喜欢
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 1970-01-01
  • 2012-09-11
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多