繁体   English   中英

随机字符串数组返回

[英]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类型,而tempint类型。 由于它们的类型不同,因此您无法分配给其他类型。 您可能要使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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM