简体   繁体   English

字符串数组的随机生成器

[英]Random Generator from String Array

I'm using Java for this problem. 我正在使用Java解决此问题。 Does anyone know how to randomly take 2 questions out of 3 question String array? 有谁知道如何从3个问题的字符串数组中随机抽取2个问题? Lets say I have a 3x5 string array like this: 可以说我有一个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"}};

The first column is the question, 2nd-4th column is the answer choices, and the 5th column is the correct answer. 第一列是问题,第二至第四列是答案选项,第五列是正确答案。 I'm trying to figure out how to randomly get 2 questions from these 3 and store those 2 questions into a one dimensional array of 2 rows in which we use the JOptionPane, for outputting, in which takes those questions from the one dimensional array and shows each question separately one by one in different windows with the answer choices included. 我试图弄清楚如何从这3个问题中随机提取2个问题,并将这2个问题存储到2行的一维数组中,在其中使用JOptionPane进行输出,其中从1维数组中获取这些问题,然后在不同的窗口中分别显示每个问题,包括答案选项。 And after answering the 2 questions, it tells the user the score based off how many questions he/she missed. 回答完两个问题后,它会根据用户错过了多少个问题告诉用户得分。

I'm relatively new to Java and it would be greatly appreciated if someone could help me with this. 我是Java的新手,如果有人可以帮助我,将不胜感激。

This is how you use random class in your case. 这就是您在情况下使用随机类的方式。 Choose a random integer, where the highest number chosen by random is your total number of questions. 选择一个随机整数,其中随机选择的最高数字是您的问题总数。

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

and you use this randomQuestion variable to access you question from the matrix: testBank[randomQuestion][0] 并且您使用此randomQuestion变量从矩阵中访问您的问题:testBank [randomQuestion] [0]

Cheers! 干杯!

Shuffling and then shortening the array is probably the way to go. 改组然后缩短数组可能是解决方法。 This is more easily done on lists however. 但是,在列表上更容易做到这一点。 In general collection classes should be preferred over arrays. 通常,集合类应该比数组更可取。

Most of the work in this answer is performed to convert the arrays to a list and back again. 此答案中的大多数工作都是将数组转换为列表然后再次返回。

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

Where questions should be set to 2 of course. 当然, questions应该设置为2。 I left out all the parameter checking. 我忽略了所有参数检查。

Note that Arrays.toList cannot be used as it simply creates a list over the backing array, and therefore the clear() operation will fail. 请注意,不能使用Arrays.toList因为它只是在后备数组上创建一个列表,因此clear()操作将失败。

Example usage: 用法示例:

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

Sorry, I'll let you do the Swing / GUI programming yourself. 抱歉,我让您自己进行Swing / GUI编程。 If you get into trouble with that ask a separate question. 如果您遇到麻烦,请提出一个单独的问题。

Here is an answer that handles the possibility that the random generator generates the same question twice. 这是一个处理随机生成器两次生成相同问题的可能性的答案。 With the code below you will only ever get 1 question asked. 使用下面的代码,您只会遇到1个问题。 Also I have commented each step to give you an idea of the logic. 我也评论了每个步骤,以使您对逻辑有所了解。 One small point if you had a 1D array of type int, then you would run into problem during the check. 一个小问题,如果您有一个int类型的1D数组,那么在检查期间就会遇到问题。 This is because 1D arrays of type int set the default value to 0. Using Integer or an ArrayList eliminates this problem because default value is null and not 0. 这是因为int类型的1D数组将默认值设置为0。使用Integer或ArrayList可以消除此问题,因为默认值为null而不是0。

I have also included the loop and JOptionPane code required to display the randomly chosen question. 我还包括了显示随机选择的问题所需的循环和JOptionPane代码。 It is up to you to decide what you want to do with the responses. 由您决定要对响应做什么。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM