如何从另一个类访问Java数组列表数据 [英] How to access Java array list data from another class

查看:185
本文介绍了如何从另一个类访问Java数组列表数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使Java中的测验,但我无法从测试仪类访问数组列表数据,因此我的问题文本没有显示出来。我有三个班;测试仪,测验接口和测验成立。我一直在玩弄了一会儿,我pretty肯定我开始让事情变得更糟,所以我想我会张贴在这里。

I'm trying to make a quiz in Java but I'm having trouble accessing the array list data from the tester class and therefore my question text isn't showing up. I have three classes; tester, quiz interface and quiz set up. I've been playing around with it for a while and I'm pretty sure I'm starting to make things worse so I thought I'd post on here.

这些问题将被添加到数组列表中测试文件,但我似乎无法访问此在设置类此方法:

The questions are added to the array list in the Tester file but I can't seem to access this in the set up class for this method:

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

预计产量是采取从数组列表随机问题并显示问题文本,但似乎不是空无一物,它是空白。

Expected output was to take a random question from the array list and display the question text but instead nothing appears and it is blank.

我是相当新的Java和编程,所以任何详细解答,欢迎!先谢谢了。

I'm fairly new to Java and programming so any detailed answers are welcome! Thanks in advance.

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;
    }


}

////////////////////////测验设立的文件。

////////////////////////quiz set up file.

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);
            }
    }

}

推荐答案

一些改动后,我能得到你的code运行。但我要提醒你,有相当一些变化:

After some alterations, I was able to get your code running. But I have to warn you, there are quite some changes:


  • QuizTester 现在只能有一个方法来启动该程序。它将初始化并填写与问题清单,然后将其传递给 QuizSetUp 实例

  • 我没有你的问题类,所以我把它降低到的ArrayList&LT;弦乐&GT; (只确保,该问题可以被传递)

  • 我没有hvae你的 QuizInterface 类,所以我顺手拿了一个小的实现,只会打印出的问题时,新的问题被置

  • QuizTester now only has a main method to start the program. It will initialize and fill the list with questions and then pass it to the QuizSetUp instance
  • I didn't have your Question class, so I reduced it to an ArrayList<String> (just to make sure, that the questions could be passed)
  • And I didn't hvae your QuizInterface class so I helped myself with a small implementation that would simply print out the question when a new question gets set

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 (只需要的主要方法)

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(); 
    }
}

这三个类可以编译,因为它们是,当我运行该程序,我得到这个输出

Those three classes can compile as they are and when I ran the program I got this output

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

我知道这是你所拥有的,唯一的我发生变化的是直接通过新创建的问题清单的 QuizSetUp 的实例 - 所以没有访问任何静态列表

I know this is a lot different from what you have, the only big change I did was passing the newly create questions list directly to the QuizSetUp instance – so no accessing any static lists.

这篇关于如何从另一个类访问Java数组列表数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆