我试图创建一个输出随机问题的代码。但是,不断出现错误“不兼容的类型:Int无法转换为Question”。我理解该错误,但是在这种情况下我无法解决该问题。我对此并不陌生,所以可能是我无法将给出的答案转换为我自己的示例。错误在以下行中:
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);
}
感谢您的帮助!
答案 0 :(得分:1)
在代码中,将名为temp
的变量声明为int
(即int index, temp;
)。稍后,您尝试为questions[i]
分配temp
的值。但是questions[i]
的类型为Question
,而temp
的类型为int
。由于它们的类型不同,因此您无法分配给其他类型。您可能希望使temp
的类型为Question
,而不是int
。
答案 1 :(得分:1)
您是否希望 temp 是问题类型?如果有帮助,请尝试下面的代码。
myVC.view.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height
{
constraint.constant = newHeight
}
}