gpt4 book ai didi

java - 返回随机字符串数组

转载 作者:行者123 更新时间:2023-11-30 02:05:47 25 4
gpt4 key购买 nike

我尝试创建一个输出随机问题的代码。但是,我不断收到错误“不兼容的类型:Int 无法转换为问题”。我理解该错误,但在这种情况下我无法找到解决方案。我对此很陌生,所以可能我无法将给定的答案翻译为我自己的示例。错误在以下行:

        questions[i]=temp;
temp = questions[index];

此片段可以在以下代码中找到:

    public static void main(String[] args){
Scanner keyboardInput = new Scanner(System.in);

System.out.println("Welcome to the geography quiz");
System.out.println("Press a key to begin");
String start = keyboardInput.nextLine();

String q1 = "What is the capital of Belgium?";
String q2 = "\nWhat is the capital of Chile?";
String q3 = "\nWhat is the capital of the Netherlands?";

Question[]questions={
new Question(q1, "Brussels", "No alternative"),
new Question(q2, "Santiago de Chile", "Santiago"),
new Question(q3, "Amsterdam", "No alternative")
};

takeTest(questions);
}

public static void takeTest(Question[]questions){
int score = 0;
int index, temp;
Scanner keyboardInput = new Scanner(System.in);

Random rnd = new Random();
for(int i= questions.length -1; i>0; i--){
index = rnd.nextInt(i+1);
questions[index] = questions[i];
questions[i]=temp;
temp = questions[index];

System.out.println(questions[i].prompt);
String a = keyboardInput.nextLine();

if (a.equalsIgnoreCase(questions[i].answer)) {
score++;
}else if(a.equalsIgnoreCase(questions[i].alternative)){
score++;
}
}
System.out.println("You got " + score + " out of " + questions.length);
}

感谢您的帮助!

最佳答案

您想要临时是问题类型吗?如果有帮助,请尝试下面的代码。

public static void takeTest(Question[]questions){
int score = 0;
int index;
Question temp;
Scanner keyboardInput = new Scanner(System.in);

Random rnd = new Random();
for(int i= questions.length -1; i>0; i--){
index = rnd.nextInt(i+1);
questions[index] = questions[i];
questions[i]=temp;
temp = questions[index];

System.out.println(questions[i].prompt);
String a = keyboardInput.nextLine();

if (a.equalsIgnoreCase(questions[i].answer)) {
score++;
}else if(a.equalsIgnoreCase(questions[i].alternative)){
score++;
}
}
System.out.println("You got " + score + " out of " + questions.length);
}

关于java - 返回随机字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433714/

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