java - 随机字符串数组返回
问题描述
我试图创建一个输出随机问题的代码。但是,我经常收到错误“不兼容的类型: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);
}
谢谢你的帮助!
解决方案
temp
在您的代码中,您声明名为int
(ie )的变量int index, temp;
。稍后,您尝试分配questions[i]
的值temp
。But questions[i]
is 属于 typeQuestion
而temp
is of type int
。由于它们具有不同的类型,因此您不能分配给另一个。您可能想要使用temp
have typeQuestion
而不是int
.
推荐阅读
- c# - 在 WPF xaml 中查找绑定的实现
- python - 如何使用py脚本根据kibana中的时间戳获取所有以前的数据?(它每次都覆盖)
- excel - 将多个工作簿中的一行复制粘贴到主工作簿
- r - 导致此错误的原因:错误 cSPADE 算法 'eid' 无效
- java - 出现错误“无法建立与节点 -1 的连接。代理可能不可用。” 在使用 kafka KStream 时
- javascript - 当我在模式中编辑评论然后返回到评论模式并删除它时出现意外错误
- javascript - 如何在react js中取消选中删除其标签的选中元素
- r - 识别数据框中的以下日期组
- r - formattable:更改列的字体并在同一列上应用 color_bar
- coldfusion - 如果只有 1 列,如何 cfloop 查询该行