【问题标题】:Problems with calling a method using an array使用数组调用方法的问题
【发布时间】:2017-12-13 13:42:06
【问题描述】:

我是 Java 新手,刚刚开始我的第一个半严肃的任务。我相信我的大部分代码都在工作,唯一的问题是因为我一直在使用类,我似乎无法将使用数组的方法调用到我的主类中。我想调用的所有其他方法似乎都有效。我想知道是否有人对此有任何解释或简单的解决方案?

提前感谢您花时间研究,非常感谢!

import java.util.Scanner;

public class GeographyQuizMain 
{

    public static void main(String[] args) 
    {
        takeQuiz();
    }

    public static void takeQuiz(Question[][] questions)
    {

        int score = 0;
        RandomNumber randomQuestion = new RandomNumber();
        //user chooses catergory
        int cat = pickCatergory();
        //ask 10 questions
        for(int i = 0; i < 10;)
        {
            Scanner answerChoice = new Scanner(System.in);
            randomQuestion.dice();
            int q = (randomQuestion.dice() - 1);
            //checks to see if question as been asked before
            if (!questions[cat][q].beenAsked)
            {
                questions[cat][q].beenAsked = true; //changes question status to beenAsked
                System.out.println(questions[cat][q].promt);
                String answer = answerChoice.nextLine();
                System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");

                if(answer.equals(questions[cat][q].answer))
                {
                    score++;
                }
                i++;
            }
        }
        System.out.println("That is the end of the quiz!\n"
                + "You got " + score + "/10");
    }

【问题讨论】:

  • 向我们展示您在Question 课程中的内容

标签: java arrays class methods


【解决方案1】:

您的问题在于通话本身,

public static void takeQuiz(Question[][] questions) 这一行声明该方法将接受名为 Question 的对象的二维数组 ([][])。 另一方面,您的电话 - takeQuiz(); 没有传递这样的数组。

您应该初始化一个这样的数组以使其编译并将其传递给函数。 IE。 Question[][] questionArray = GenerateQuestionArray(); //you should write this method takeQuiz(questionArray);

正如您所说,很明显您是 Java 新手,我强烈建议您阅读课堂上提供给您的说明和信息。我敢打赌,那里涵盖了对象初始化、方法和数组的详细信息。

【讨论】:

    【解决方案2】:

    您的方法调用似乎存在问题,在您的方法 takeQuiz();正在使用二维数组来提问,但在调用时您没有提供该参数,因此编译器无法找到该方法。 这就是问题所在。

    尝试像这样使用,这是一个简单的例子。将其替换为您的实际值。

    String[][] questions= new String[3][3];

    参加测验(问题);

    这会起作用。

    【讨论】:

      【解决方案3】:

      你调用了你的方法takeQuiz(),但实际上并没有提供它的参数Question[][] questions

      【讨论】:

        猜你喜欢
        • 2014-01-16
        • 2011-07-24
        • 2011-09-13
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 2013-02-09
        • 1970-01-01
        相关资源
        最近更新 更多