Java 基于字符串数组的随机发生器

Java 基于字符串数组的随机发生器,java,arrays,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 b

我正在使用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进行输出,其中从一维数组中获取这些问题,并在不同的窗口中逐个显示每个问题,包括答案选项。在回答了这两个问题后,它会根据用户错过的问题数量告诉用户分数


我对Java比较陌生,如果有人能帮助我,我将不胜感激

这就是在您的案例中使用random类的方式。选择一个随机整数,其中随机选择的最大数字是您的问题总数

Random random = new Random();
int randomQuestion = random.nextInt(nrOfQuestions);
您可以使用这个randomQuestion变量访问矩阵中的问题: 测试银行[问题][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;
}

抱歉,我将让您自己进行Swing/GUI编程。如果你在这方面遇到麻烦,可以问一个单独的问题。

这里有一个答案,可以处理随机生成器两次生成相同问题的可能性。使用下面的代码,您只会被问到一个问题。此外,我还对每一步都进行了评论,让您了解其中的逻辑。一个小问题是,如果您有一个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;
}
publicstaticvoidmain(字符串参数[]){
//我们之所以设置最后一个变量,是因为我们不想将数字硬编码到循环中
最终问题的整数=2;
字符串测试库[][]={{“草是什么颜色?”,“A.绿色”,“B.红色”,“C.粉色”,“A”},
{“第一个月叫什么?”,“A.十二月”,“B.一月”,“C.三月”,“B”},
{“足球是什么形状的?”、“a.正方形”、“B.扁平”、“C.圆形”、“C”};
//初始化随机选择的一系列问题。
字符串finalarayofquestions[]=新字符串[要接受的问题数量];
//ArrayList来存储问题的索引号,以便稍后我们可以检查数字生成器是否已使用该索引号
ArrayList alreadyChosenList=新的ArrayList();
//我们将用于判断是否已选择问题的布尔值
布尔型alreadyChosen;
//随机数生成器生成的列号,然后用于提取字符串问题
内敛;
//for循环用于循环整个过程,具体取决于您想回答的问题数量。
for(int i=0;i<要回答的问题数量;i++){
//生成一个随机数,重复这个过程(do/while),直到生成了一个以前没有生成过的随机数
做{
//在范围内生成一个随机数
随机=新随机();
rowToUse=random.nextInt(testBank.length);
//支票尚未被取走
alreadyChosen=alreadyChosen(rowToUse,ALREADYCHOSENST);
}while(alreadyChosen);
//获取随机选择的问题的字符串表示形式
字符串questionselected=testBank[rowToUse][0];
//将此字符串添加到finalListOfQuestions
最后一组问题[i]=选择的问题;
//添加到已选择的问题列表中。确保同一问题不会重复两次。
//alreadyChosenList[i]=alreadyChosenList[rowToUse];
alreadychoslist.add(rowToUse);
}
用于(字符串问题:最后一组问题){
String response=JOptionPane.showInputDialog(问题);
/*
响应是用户键入的答案。在这里,您可以对照已有的数组进行检查
或者,如果您不希望用户输入响应,请使用:
showMessageDialog(空,问题);
*/
}
}
/*
方法获取要使用的行索引和已使用的行索引的ArrayList,并根据当前索引是否在ArrayList中返回true或false
*/
私有静态布尔值alreadyChosen(int-rowToUse,ArrayList-alreadychossen){
for(int indexToCheck:alreadyChosenList){
if(indexToCheck==rowToUse){
返回true;
}
}
返回false;
}

您可以使用
随机
nextInt(int n)
。看一看api,我读了你发给我的链接,但它似乎真的让我困惑。我对Java非常陌生,所以如果你知道我的意思的话,我的代码效率不高。如果你或任何人能根据我写下的信息创建一个例子,并向我解释,那将非常有帮助。我基本上是一个视觉学习者。你好,蓝,欢迎来到SO。你通常希望你的问题更精确一点。你对问题的哪一部分有问题(选择随机问题、如何将其放入数组、如何使用JOptionPane、如何在窗口中显示、如何告诉用户分数等)?你已经试过什么了?为什么不起作用?为什么旁边的“相关问题”对你没有帮助?你好。我知道如何使用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;
}