首页 > 解决方案 > 随机字符串数组返回

问题描述

我试图创建一个输出随机问题的代码。但是,我经常收到错误“不兼容的类型: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);
}

谢谢你的帮助!

标签: javaarraysstringrandom

解决方案


temp在您的代码中,您声明名为int(ie )的变量int index, temp;。稍后,您尝试分配questions[i]的值temp。But questions[i]is 属于 typeQuestiontempis of type int。由于它们具有不同的类型,因此您不能分配给另一个。您可能想要使用temphave typeQuestion而不是int.


推荐阅读