【问题标题】:How to access Java array list data from another class如何从另一个类访问 Java 数组列表数据
【发布时间】:2014-09-11 22:48:44
【问题描述】:

我正在尝试用 Java 进行测验,但我无法从测试器类访问数组列表数据,因此我的问题文本没有显示。我有三门课;测试仪,测验界面和测验设置。我已经玩了一段时间了,我很确定我开始让事情变得更糟,所以我想我会在这里发帖。

问题已添加到测试器文件中的数组列表中,但我似乎无法在此方法的设置类中访问它:

public void setQuestion(int randIndex) {
    qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
}

预期的输出是从数组列表中随机抽取一个问题并显示问题文本,但没有出现任何内容并且它是空白的。

我对 Java 和编程还很陌生,所以欢迎任何详细的答案!提前致谢。

import java.util.ArrayList;

public class QuizTester {
    private static ArrayList<Question> questions; //declares arrayList to holds the questions

    public static void main(String[] args) {
            QuizSetUp theQuiz = new QuizSetUp();
            questions = new ArrayList<Question>(); //constructor

            questions.add(new FillInBlank("____________ is the ability of an object to take many forms.", "Polymorphism"));
            questions.add(new FillInBlank("The process where one object acquires the properties of another is called __________", "inheritance"));
            questions.add(new FillInBlank("The ___________ keyword is used by classes to inherit from interfaces", "implements"));
            questions.add(new MultipleChoice("Which programming technique can be used to prevent code and data from being randomly accessed by other code defined outside the class?",
                            "Polymorphism", "Encapsulation", "Inheritance", "Construction", "Encapsulation"));
            theQuiz.pickQuestion();


    }
    public ArrayList<Question> getQuestionList() {
            return this.questions;
    }


}

/////////////////////测验设置文件。

public class QuizSetUp {
    private QuizInterface qi;
    private QuizTester test;
    //private ArrayList<Question> questions; //declares arrayList to holds the questions
    private int counter = 1;
    Random random;
    int randIndex;

    public QuizSetUp() {
            setInterface();
            //questions = new ArrayList<Question>(); //constructor
    }
    private enum QuAnswer { CORRECT,INCORRECT }

    public void setInterface() {
            qi = new QuizInterface();
            test = new QuizTester();

            //add action listeners to each of the buttons
            ActionListener cl = new ClickListener();
            qi.getNextBtn().addActionListener(cl);
            qi.getStartQuizBtn().addActionListener(cl);

            //allows users to press enter to start quiz rather than having to click quiz button
    KeyListener ent = new KeyBoardListener();
    qi.getUName().addKeyListener(ent);
    qi.getUPassword().addKeyListener(ent);

    }



    public void pickQuestion() {
            randQuestion();
            setQuestion(randIndex);
            //setAnswer("A", randIndex);
            //setAnswer("B", randIndex);
            //setAnswer("C", randIndex);
            //setAnswer("D", randIndex);
            //setCorrectAnswer(randIndex);
            //qi.resetTimer();

    }

    public void setQuestion(int randIndex) {
            qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());
    }

    public void setNextQuestion() {
            //qi.getTimer().cancel();
            //qi.cancelInterval();
            if (counter < 5) { //users must answer five questions to complete quiz
                    pickQuestion();
            } else {
                    //JOptionPane.showMessageDialog(qi.getPanels(), "End of quiz");
                    //switch to end panel to show results of quiz
            }
    }

    public int randQuestion() {
            random = new Random();
            randIndex = random.nextInt(questions.size());
            return randIndex;
    }

    //inner listener class for buttons
    private class ClickListener implements ActionListener {
            public void actionPerformed(ActionEvent evt) {
                    if (evt.getSource() == qi.getStartQuizBtn()) {
                            qi.setEnteredName(qi.getUName().getText());
                            qi.setEnteredPass(qi.getUPassword().getPassword());
                            validateInput();
                    } else if (evt.getSource() == qi.getNextBtn()) {
                            counter++;
                            if (counter == 5) {
                                    qi.getNextBtn().setText("Finish Quiz"); //changes next button text on final question
                            }
                            if (counter < 6) {
                                    qi.getQuProgress().setText(counter + " of 5");
                            } else {
                                    //shuffle to end panel
                            }
                    }
            }
    }

    //inner listener class for key presses
    private class KeyBoardListener implements KeyListener {
            public void keyPressed(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                            qi.setEnteredName(qi.getUName().getText());
                            qi.setEnteredPass(qi.getUPassword().getPassword());
                            validateInput();
                    }
            }
            @Override
            public void keyReleased(KeyEvent e) {
                    // TODO Auto-generated method stub

            }
            @Override
            public void keyTyped(KeyEvent e) {
                    // TODO Auto-generated method stub

            }
    }

    //method to validate input by user to log in
    public void validateInput() {
            //presence check on username
            if (qi.getEnteredName().length() > 0) {
                    //presence check on password
                    if (qi.getEnteredPass().length > 0) {
                            //ensures password is at least 6 char long
                            if(qi.getEnteredPass().length > 5) {
                                    qi.getCards().next(qi.getPanels()); //getPanels() == cardPanel
                            } else {
                                    JOptionPane.showMessageDialog(null,
                                                    "Your password must be at least six characters long.",
                                                    "Password Violation", JOptionPane.WARNING_MESSAGE);
                            }
                    } else {
                            JOptionPane.showMessageDialog(null,
                                            "Your did not enter a password.",
                                            "Password Violation", JOptionPane.WARNING_MESSAGE);
                    }
            } else {
                    JOptionPane.showMessageDialog(null,
                                    "You did not enter a username. Please try again.",
                                    "Username Violation", JOptionPane.WARNING_MESSAGE);
            }
    }

}

【问题讨论】:

  • 你能自己在这里发布你的代码吗?我不会点击一些随机链接来帮助你:)
  • 此外,更详细的问题描述、预期和实际行为也会有所帮助。
  • 提前一个提示:如果我是你,我不会在一个语句中传递这么多方法调用。首先获取QuestionList-entry,然后获取其文本并使用System.out.println(..) 打印出来。这样你就可以在第一时间看到是否可以得到文本。只有这样我才会将此文本设置为qi。但即使在那里,我也会创建一个新方法qi.setQuText(),这样您就不必先调用qi.getQuText()。简而言之:更多的代码行更容易调试:)
  • 感谢 GameDroids。我尝试放置一个打印语句,并且数组列表的输出为空。所以我猜我没有访问我添加问题的数组列表,而是一个空的。仍然不确定如何访问它:(
  • 好吧,我仍然不确定错误出在哪里,但也许你可以尝试以另一种方式传递 questions 列表,也许在你的 QuizSetUpsetQuestions(ArrayList questions){this.questions = questions;} 中使用你的方法直接在QuizSetUp 类中的问题列表,访问它会更容易(QuizTester 类中没有静态列表)

标签: java arrays object arraylist


【解决方案1】:

经过一些修改,我能够让您的代码运行。但我必须警告你,有很多变化:

  • QuizTester 现在只有 main 方法来启动程序。它将初始化并用问题填充列表,然后将其传递给QuizSetUp 实例
  • 我没有你的Question 课程,所以我把它减少到ArrayList&lt;String&gt;(只是为了确保问题可以通过)
  • 而且我没有使用您的 QuizInterface 课程,所以我帮助自己完成了一个小型实现,当设置了新问题时,它会简单地打印出问题

QuizInterface(小助手类)

public class QuizInterface {

    private String text;

    public QuizInterface() {
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
        System.out.println("question text = "+this.text);  // this is just to make sure it worked
    }
}

QuizSetUp(大幅减少)

public class QuizSetUp {

    private QuizInterface qi;
    private ArrayList<String> questions; // uncommented, it's needed now
    private int counter = 1;
    Random random;
    int randIndex;

    // I chose to pass the list with the constructor but the setQuestions() will do as well
    public QuizSetUp(ArrayList<String> questions) {
        this.questions = questions;
        setInterface();
    }

    // NEW method – but it's not needed
    public ArrayList<String> getQuestions() {
        return questions;
    }

    // NEW method – but it's not needed
    public void setQuestions(ArrayList<String> questions) {
        this.questions = questions;
    }

    private enum QuAnswer {
        CORRECT, INCORRECT
    }

    public void setInterface() {
        qi = new QuizInterface();
//        test = new QuizTester();   // this is no longer needed since QuizTester is only used to start the program
    }

    public void pickQuestion() {
        randQuestion();
        setQuestion();   // randIndex is already a global variable in this class, no need to pass with the method call
    }

    public void setQuestion() {
        // QuizInterface has a new method now called "setText()"
        // so here we access the list "questions" (it is already initialized, because we pass it to this class when constructing it)
        // this.randIndex is global, so we can use it directly in this method as an index to the questions list (as you already did it)
        qi.setText(this.questions.get(this.randIndex));
    }

    public void setNextQuestion() {
        //qi.getTimer().cancel();
        //qi.cancelInterval();
        if (counter < 5) { //users must answer five questions to complete quiz
            pickQuestion();
        } else {
            //JOptionPane.showMessageDialog(qi.getPanels(), "End of quiz");
            //switch to end panel to show results of quiz
        }
    }

    public int randQuestion() {
        random = new Random();
        randIndex = random.nextInt(questions.size());
        return randIndex;
    }
 // .... the rest I left out here because it is not needed for this little test
}

QuizTester(只需要main方法)

public class QuizTester {

    public static void main(String[] args) {
        ArrayList<String> questions = new ArrayList<>(); //as you can see I replaced the List with a list of Strings (because I didn't have your Question class)

        // so these are only strings... 
        questions.add("____________ is the ability of an object to take many forms.");
        questions.add("The process where one object acquires the properties of another is called __________");
        questions.add("The ___________ keyword is used by classes to inherit from interfaces");
        questions.add("Which programming technique can be used to prevent code and data from being randomly accessed by other code defined outside the class?");

        // here I create the QuizSetUp instance and pass the list right with the constructor
        QuizSetUp theQuiz = new QuizSetUp(questions);
        // if everything works out, calling this method 
        // should pick a new question, set it to the QuizInterface
        // and the QuizInterface (the helper version I made) will print it out
        theQuiz.pickQuestion(); 
    }
}

这三个类可以按原样编译,当我运行程序时,我得到了这个输出

question text = The ___________ keyword is used by classes to inherit from interfaces

我知道这与您所拥有的有很大不同,我所做的唯一 更改是将新创建的问题列表直接传递给 QuizSetUp 实例 - 所以没有访问任何静态列表。

【讨论】:

  • 虽然我很佩服你的努力,但我想知道花这么多时间修复“狗早餐”代码是否真的符合任何人的利益。
  • 是的,你可能是对的——尤其是当 error 很小的时候。下次我会三思而后行,然后再直接解决这个问题:)
【解决方案2】:

看这一行:

qi.getQuText().setText(getQuestionList().get(randIndex).getQuestionText());

getQuestionList() 在哪里实现?它看起来像一个方法调用,只是QuizSetUp 没有声明getQuestionList() 方法。它属于不同的类别。

结论:您在问题中向我们展示的代码甚至无法编译。


我应该指出,这(QuezSetup)的风格非常糟糕,容易引起混淆。

private static ArrayList<Question> questions;

public ArrayList<Question> getQuestionList() {
        return this.questions;
}

虽然this.questions 看起来好像是在引用一个实例变量,但实际上它是在引用一个静态变量。 this 具有误导性。

【讨论】:

  • 不,唯一的主要方法是在 Tester 类中。如果您有时间来找我,我可以通过电子邮件将项目中的所有课程发给您吗?我真的很感激。
  • 不行。对不起。你需要学习如何调试自己的代码……学习调试的最好方法就是去做。
猜你喜欢
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 2012-05-03
相关资源
最近更新 更多