【问题标题】:getting five random elements out of a java array从java数组中获取五个随机元素
【发布时间】:2018-09-12 22:35:50
【问题描述】:

我已经在这个项目上工作了几天,我能够完成大部分工作,但我一直在努力从我的阵列中取出五个不同的项目。我可以选择五次相同的项目。

我的代码如下所示:

public class CardGuessingGame {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String[] myCards = new String[]{"two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"}; // Array for cards

        Random rand = new Random(); //random construction
        rand.nextInt(13); // Sets rand to 0-12 int
        //int randomNums = rand.nextInt(13); // sets randNums from 0-12
        int randomNums = rand.nextInt(myCards.length); //Randomizes "randomNums to the length of the array"
        String cardInHand = myCards[(int)randomNums];

        for (randomNums=0; randomNums < 5; randomNums++) {

            System.out.println(cardInHand);
        }

        System.out.print("Guess the card in my hand: "); // Prints to user asking for guess

        Scanner answer = new Scanner(System.in); // gets user input
        String s = answer.nextLine(); //stores user input inside variable s

        if(s.equals(cardInHand)) {

            System.out.println("I do have that card in hand");
        } else {

            System.out.println("I do not have that card in hand!");
        }

        System.out.print("These were the cards I had in hand: ");
        System.out.println(cardInHand);
    }
}

这是输出

run:
four
four
four
four
four
Guess the card in my hand: four
I do have that card in hand
These were the cards I had in hand: four

我现在拥有的东西可以工作,但不正确。

【问题讨论】:

  • 工作但不正确,所以换句话说它不工作:)
  • 您只选择一个cardInHand,然后在for 循环中使用randomNums 打印单个cardInHand
  • 你有没有试过和你的导师或助教一起复习你的工作?这里的人可能会向您展示工作代码,但您可以通过对话了解您可能遗漏或误用的概念。
  • pjs,今天和我的教授交谈并让他查看代码,他指出我应该使用循环,因为我有 5 个打印语句(不是这个程序的主要问题,但是无论如何修复了那部分。)试图指出我的程序发生了什么,但他并没有真正帮助,这就是我在堆栈上的原因。
  • 如果要保证不同的卡,可以考虑使用Collections.shuffle。然后遍历洗牌列表以获得所需数量的项目。如果您使用随机选择,即使您更正了当前仅调用nextInt 一次的错误,您也可以获得重复。顺便说一句,如果您希望用户看到您的评论,请在他们的用户名前加上“@”,例如“@pjs”。

标签: java arrays random


【解决方案1】:
  1. 我认为您对 rand.nextInt(13) 的作用存在误解。在这里,您正确地创建了 random 对象,但是第二行,您认为它将 rand 设置为 0-12,而实际上它只是调用一个方法来返回一个从 0-12 的随机整数,并且完全没有做任何事情。

    Random rand = new Random(); //random construction
    rand.nextInt(13); // Sets rand to 0-12 int
    
  2. 一个。您将变量 randomNums 设置为某个随机值,我不知道为什么,当您在 for 循环中将其重置为零之前,然后再进行任何可能的使用。

    b.您存储卡片的一般方法是不正确的,因为您应该创建一个新的 ArrayList 来存储 5 张卡片,但实际上,您只生成了一张卡片并打印了 5 次

    int randomNums = rand.nextInt(myCards.length);
    String cardInHand = myCards[(int)randomNums];
    for (randomNums=0; randomNums < 5; randomNums++) {
        System.out.println(cardInHand);
    }
    

这就是您的代码的更简洁、更合乎逻辑的版本应该是什么样子。

String[] myCards = {"two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"};
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int cardIndex = rand.nextInt(myCards.length);
ArrayList<String> playerHand = new ArrayList<>();
for (int i = 0; i < 5; i++) {
    while (playerHand.contains(myCards[cardIndex]))
        cardIndex = rand.nextInt(myCards.length);
    playerHand.add(myCards[cardIndex]);
}
System.out.print("Guess the card in my hand: ");
if(playerHand.contains(scan.nextLine()))
    System.out.println("I do have that card in hand");
else
    System.out.println("I do not have that card in hand!");
System.out.print("These were the cards I had in hand: ");
System.out.println(playerHand);

【讨论】:

    【解决方案2】:

    我编写了新代码来加深您在阅读源代码时的歧义。因此,我在某些行中添加了注释以清楚地理解。

    public class CardGuessingGame  {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
    
    
            //list of cards
            List<String> myCards = Arrays.asList("two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace");
            //shuffle cards
            Collections.shuffle(myCards);
    
            //get first 5 elements from shuffled list
            HashSet<String> myHand = new HashSet<>();
            for (int i = 0; i < 5; i++) {
                myHand.add(myCards.get(i));
                System.out.println(myCards.get(i));
            }
    
            System.out.print("Guess the card in my hand: "); // Prints to user asking for guess
    
            Scanner answer = new Scanner(System.in); // gets user input
            String s = answer.nextLine(); //stores user input inside variable s
    
            //if set contains , you found the card
            if (myHand.contains(s)) {
                System.out.println("I have that card in my hand");
            } else {
                System.out.println("I do not have that card in hand!");
            }
    
            System.out.print("These are the cards which is in my hand: ");
            //write all cards in my hand with sepearete comma
            System.out.println(String.join(",", myHand));
        }
    }
    

    【讨论】:

      【解决方案3】:

      这是一个有效的代码,只需要唯一的卡片。首先,您应该知道哪些变量是数组,哪些不是。

      rand.nextInt(13); 的调用不会将 Random 实例设置为生成 1 到 13 之间的随机数,但实际上会生成一个。

      你的随机数生成应该放在循环中。手头的卡片需要包含多个值,因此应使用数组。

      import java.util.Arrays;
      import java.util.Collections;
      import java.util.LinkedList;
      import java.util.List;
      import java.util.Scanner;
      
      public class CardGuessingGame {
      
          /**
           * @param args
           *            the command line arguments
           */
          public static void main(String[] args) {
      
              String[] myCards = new String[] { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
                      "jack", "queen", "king", "ace" }; // Array for cards
      
              //Random rand = new Random(); // random construction
              //rand.nextInt(13); // Sets rand to 0-12 int
              // int randomNums = rand.nextInt(13); // sets randNums from 0-12
      
              String[] cardsInHand = new String[5];
      
              List<String> cards = new LinkedList<>(Arrays.asList(myCards));
              Collections.shuffle(cards);
      
              for (int i = 0; i < 5; i++) {
                  //This will not give you unique cards!
                  //int randomNums = rand.nextInt(myCards.length); // Randomizes "randomNums to the length of the array"
                  cardsInHand[i] = cards.remove(0);
              }
      
              System.out.println(Arrays.toString(cardsInHand));
      
              System.out.print("Guess the card in my hand: "); // Prints to user asking for guess
      
              Scanner answer = new Scanner(System.in); // gets user input
              String s = answer.nextLine(); // stores user input inside variable s
      
      
              //Some kind of contains method. You can traverse the array use a list or do however you like
              Arrays.sort(cardsInHand);
      
              if (Arrays.binarySearch(cardsInHand,s) >= 0) {
      
                  System.out.println("I do have that card in hand");
              } else {
      
                  System.out.println("I do not have that card in hand!");
              }
      
              //Close the stream
              answer.close();
      
              System.out.print("These were the cards I had in hand: ");
              System.out.println(Arrays.toString(cardsInHand));
      
          }
      }
      

      【讨论】:

        【解决方案4】:

        首先,我将尝试解释你哪里出错了,并给你和工作代码的例子。

        我假设您应该只为此使用数组,并且您不能重复数字。

        第一

        您将cardInHand 设置为myCards[(int)randomNums]。然后循环5 次并将cardInHand 打印到控制台。您永远不会将卡片设置为其他任何东西。

        第二

        即使您将cardInHand 设置为其他值,您现在也丢失了之前的卡信息。您缺少的是另一个用于保存卡信息的数组。这可以通过使用循环来完成。

        for(int i = 0; i < 5; i++)
        {
            cardInHand = myCards[rand.nextInt(myCards.length)];
            cardsInHand[i] = cardInHand;
        }
        

        这样就实现了将卡片保存到数组中以备后用。

        这是解决您的问题的有效代码。

        String[] myCards = new String[]{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "jack", "queen", "king", "ace"};
        Random rand = new Random();
        String[] cardsInHand = new String[5];
        int[] usedNums = new int[5];
        
        for(int i = 0; i < 5; i++)
        {
            usedNums[i] = -1;
        }
        
        for(int i = 0; i < 5; i++)
        {
            int randNum = rand.nextInt(myCards.length);
            boolean contains = false;
            do
            {
                for(int j = 0; j < 5; j++)
                {
                    if(usedNums[j] != randNum)
                    {
                        contains = false;
                        continue;
                    }
                    contains = true;
                    randNum = rand.nextInt(myCards.length);
                }
            }
            while(contains);
            cardsInHand[i] = myCards[randNum];
            usedNums[i] = randNum;
        }
        
        Scanner answer = new Scanner(System.in);
        String s = answer.nextLine();
        
        boolean hasCard = false;
        
        for(int i = 0; i < 5; i++)
        {
            if(cardsInHand[i].equals(s)
            {
                hasCard = true;
                break;
            }
        }
        
        if(hasCard)
        {
            System.out.println("Has card");
        }
        else
        {
            System.out.println("Not has card");
        }
        
        System.out.println("Cards in hand:");
        for(int i = 0; i < 5; i++)
        {
            System.out.println(cardsInHand[i]);
        }
        

        如果您可以使用重叠数字,则删除对 usedNumsdo..while 循环的引用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-03
          • 1970-01-01
          • 2015-01-31
          • 1970-01-01
          • 2012-02-16
          • 2018-10-23
          • 2021-04-29
          • 2019-12-10
          相关资源
          最近更新 更多