【发布时间】:2018-07-20 01:05:38
【问题描述】:
我尝试创建一个输出随机问题的代码。但是,我经常收到错误“不兼容的类型:Int 无法转换为问题”。我理解这个错误,但我无法为这种情况找到解决方案。我对此很陌生,所以我可能无法将给定的答案翻译成我自己的例子。错误在以下几行中:
questions[i]=temp;
temp = questions[index];
这个sn-p可以在以下代码中找到:
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);
}
感谢您的帮助!
【问题讨论】:
-
这个错误还不够清楚明白吗?您刚刚将
int分配给了Question类型。 -
甜蜜!只要回答“别无选择”,我就能得到 66%!
-
@Elliott Frisch 这是我调查的下一部分。如何摆脱那部分。但为了让它发挥作用,我不得不暂时搁置它。感谢您的提醒..
-
@Jai 当然我理解这个错误,我只是不知道如何摆脱这个错误,因为我的输入总是一个字符串值,我在这个网页上找到的解决方案总是让我进入这个错误。
-
如果允许,使用列表。