[英]Random String array return
我試圖創建一個輸出隨機問題的代碼。 但是,不斷出現錯誤“不兼容的類型: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);
}
謝謝你的幫助!
在您的代碼中,將名為temp
的變量聲明為int
(即int index, temp;
)。 稍后,您嘗試分配questions[i]
temp
的值。 但是questions[i]
是Question
類型,而temp
是int
類型。 由於它們的類型不同,因此您無法分配給其他類型。 您可能要使temp
具有Question
類型而不是int
類型。
您是否要使溫度為“問題”類型? 如果有幫助,請嘗試下面的代碼。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.