gpt4 book ai didi

java随机数组

转载 作者:行者123 更新时间:2023-12-02 00:47:26 25 4
gpt4 key购买 nike

我想让问题随机,当我给出答案时比较它们是否是正确答案?有人可以给我一点帮助吗?

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Random;

public class Main {

public static void main(String[] args) {


String[] aa = { "question aa" };
String[] bb = { "question bb"};
String[] cc = { "question cc"};
String[] dd = { "question dd"};

String[] e = { "answer to question aa" };
String[] f = { "answer to question bb"};
String[] g = { "answer to question cc"};
String[] h = { "answer to question dd"};



// should be here the random question

System.out.print("Enter your answer: ");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String userAnswer = null;

try {
userAnswer = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your answer!");
System.exit(1);
}

System.out.println("Thanks for the answer, " + userAnswer);

}

最佳答案

class QuestionAnswer{
String q;
String a;
//getters/setters and const.
}

1 创建 DS,因为您的问题集较小,建议保留在内存中

List<QuestionAnswer> lst = new ArrayList<QuestionAnswer>();
lst.add(new QuestionAnswer("Question1","Answer1"));
lst.add(new QuestionAnswer("Question2","Answer2"));
lst.add(new QuestionAnswer("Question3","Answer3"));

2 生成 0 到 list.size() 之间的随机整数

Random r = new Random();
int index = r.nextInt(lst.size());

3获取问题并打印并接受用户的回答

System.out.println(lst.get(index).getQ());
Scanner in = new Scanner(System.in);
// Reads a single line from the console
String answer = in.nextLine();

4将用户的答案与列表进行比较

if(answer.equalsIgnoreCase(lst.get(index).getA())){
System.out.println("You are correct. !!");
}

关于java随机数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4553487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com