字符串数组的随机生成器

时间:2014-12-06 00:28:28

标签: java arrays

我正在使用Java来解决这个问题。有谁知道如何从3个问题字符串数组中随机抽取2个问题?假设我有一个像这样的3x5字符串数组:

String TestBank[][] = {{"What color is grass?","A. Green","B. Red","C. Pink","A"},
{"Whats the first month called?","A. December","B. January","C. March","B"},
{"What shape is a soccer ball?","A. square","B. flat","C. round","C"}};

第一列是问题,第二至第四列是答案选择,第五列是正确答案。我试图弄清楚如何从这3个中随机获得2个问题并将这2个问题存储到2行的一维数组中,我们在其中使用JOptionPane进行输出,其中从一维中获取这些问题数组并在不同的窗口中逐个显示每个问题,包括答案选项。在回答了2个问题后,它会根据用户错过的问题告诉用户得分。

我对Java相对较新,如果有人可以帮助我,我将不胜感激。

3 个答案:

答案 0 :(得分:1)

这就是你在你的情况下使用随机类的方法。选择一个随机整数,其中随机选择的最大数字是您的总问题数。

Random random = new Random();
int randomQuestion = random.nextInt(nrOfQuestions);

并使用此randomQuestion变量从矩阵中访问您的问题: 题库[randomQuestion] [0]

干杯!

答案 1 :(得分:0)

改组然后缩短阵列可能是要走的路。但是,这更容易在列表上完成。通常,集合类应优先于数组。

执行此答案中的大部分工作是为了将数组转换为列表并再次返回。

private static String[][] randomize(String[][] testBank, int questions) {
    // convert top array to list of mutable size 
    List<String[]> testBankAsList = new ArrayList<>();
    for (String[] qoa: testBank) {
        testBankAsList.add(qoa);
    }

    // randomize questions
    Collections.shuffle(testBankAsList, new SecureRandom());

    // remove the tail
    testBankAsList.subList(questions, testBankAsList.size()).clear();

    // convert back into array
    String[][] shorterRandomTestBank = testBankAsList.toArray(new String[testBankAsList.size()][]);

    return shorterRandomTestBank;
}

当然questions应该设置为2。我遗漏了所有的参数检查。

请注意,Arrays.toList无法使用,因为它只是在支持数组上创建一个列表,因此clear()操作将失败。

使用示例:

public static void main(String[] args) {
    String testBank[][] = {{"What color is grass?","A. Green","B. Red","C. Pink","A"},
            {"Whats the first month called?","A. December","B. January","C. March","B"},
            {"What shape is a soccer ball?","A. square","B. flat","C. round","C"}};
    int questions = 2;

    String[][] shorterRandomTestBank = randomize(testBank, questions);

    // iterate of the returned questions
    for (String[] qoa : shorterRandomTestBank) {
        // prints the question
        System.out.println(qoa[0]);

        // prints the answer
        System.out.println(qoa[qoa.length - 1]);
    }
}

抱歉,我允许您自己进行Swing / GUI编程。如果你遇到麻烦就问一个单独的问题。

答案 2 :(得分:0)

这是一个答案,它处理随机生成器两次生成相同问题的可能性。使用下面的代码,您只会遇到1个问题。我还评论了每一步,让您了解逻辑。如果你有一个类型为int的1D数组,那么你应该在检查期间遇到问题。这是因为int类型的1D数组将默认值设置为0.使用Integer或ArrayList可以消除此问题,因为默认值为null且不为0.

我还包含了显示随机选择的问题所需的循环和JOptionPane代码。您可以自行决定要对回复做什么。

public static void main(String args[]) {

    // We are setting this final variable because we don't want to hard code numbers into loops etc
    final int NUMBER_OF_QUESTIONS_TO_TAKE = 2;

    String testBank[][] = {{"What color is grass?", "A. Green", "B. Red", "C. Pink", "A"},
            {"Whats the first month called?", "A. December", "B. January", "C. March", "B"},
            {"What shape is a soccer ball?", "A. square", "B. flat", "C. round", "C"}};

    // Initialise the array of questions that have been randomly chosen.
    String finalArrayOfQuestions[] = new String[NUMBER_OF_QUESTIONS_TO_TAKE];

    // ArrayList to store the index number of a question so we can check later if it has been already used by number generator
    ArrayList<Integer> alreadyChosenList = new ArrayList<Integer>();

    // boolean that we will use for whether or not a question has already been selected
    boolean alreadyChosen;

    // The column number that the random number generator generates, which is then used to extract the String question
    int rowToUse;

    // A for loop is used to loop through the process, depending on how many questions you want to take.
    for (int i = 0; i < NUMBER_OF_QUESTIONS_TO_TAKE; i++) {

        // Generate a random number, repeat the process (do/while) until a random number has been generated that hasnt been generated before
        do {
            // Generate a random number within the range
            Random random = new Random();
            rowToUse = random.nextInt(testBank.length);

            //check not already been picked
            alreadyChosen = alreadyChosen(rowToUse, alreadyChosenList);
        } while (alreadyChosen);


        // Get String representation of question chosen at random
        String questionChosen = testBank[rowToUse][0];

        // Add this String to finalListOfQuestions
        finalArrayOfQuestions[i] = questionChosen;

        // adds to list of questions already chosen. Makes sure you don't take same question twice.
        //alreadyChosenList[i] = alreadyChosenList[rowToUse];
        alreadyChosenList.add(rowToUse);
    }

    for (String questions : finalArrayOfQuestions) {
        String response = JOptionPane.showInputDialog(questions);

        /*
        The response is the answer that the user types in. Here you can check it against the arrays you have
        Or if you dont want the user to input a response use:
         JOptionPane.showMessageDialog(null, questions);
         */

    }
}


/*
Method takes row index to use and the ArrayList of row indexes already been used and returns true or false depending if the current one is in the arraylist
 */
private static boolean alreadyChosen(int rowToUse, ArrayList<Integer> alreadyChosenList) {

    for (int indexToCheck : alreadyChosenList) {
        if (indexToCheck == rowToUse) {
            return true;
        }
    }
    return false;
}