从java数组中获取五个随机元素

问题描述 投票:0回答:4

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

这是我的代码的样子:

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

我现在有什么用,但不正确。

java arrays random
4个回答
0
投票
  1. 我认为你对rand.nextInt(13)的作用有误解。在这里你正确地创建了你的随机对象然而第二行,你认为它的设置rand为0-12,当它实际上只是调用一个方法来返回一个0-12的随机整数并且完全没有做任何事情。 Random rand = new Random(); //random construction rand.nextInt(13); // Sets rand to 0-12 int
  2. 一个。你将变量randomNums设置为一些随机值,我不知道为什么,当你在任何可能的使用之前将它在for循环中重置为零时。 湾您存储卡的一般方法是不正确的,因为您应该制作一个新的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);

0
投票

我在编写源代码时编写了新代码来解决问题。所以我在一些行中添加了评论以便清楚地理解。

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

0
投票

这是一个有效的代码,只采用独特的卡片。首先,你应该得到一个喘气,你的变量是阵列,哪些不是。

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

    }
}

0
投票

首先,我将尝试解释您出错的地方,并提供工作代码示例。

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

第一

你将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循环的引用。

© www.soinside.com 2019 - 2024. All rights reserved.