如何从另一个类访问Java数组列表数据

2023-12-26

我正在尝试用 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);
            }
    }

}


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

  • QuizTester现在只有一个main方法来启动程序。它将初始化并用问题填充列表,然后将其传递给QuizSetUp实例
  • 我没有你的Question类,所以我将其简化为ArrayList<String>(只是为了确保问题可以通过)
  • 而我却没有你的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
    }
}

测验设置(大幅减少)

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
}

测验测试仪(只需要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

我知道这和你所拥有的有很大不同,唯一的big我所做的更改是将新创建的问题列表直接传递给QuizSetUp实例 – 因此无法访问任何静态列表。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从另一个类访问Java数组列表数据 的相关文章

  • Gradle 发布两次尝试将 RPM 上传到 Artifactory YUM 存储库,第二次失败并显示 403

    我正在尝试使用 gradle 和 ivy publish 插件将 RPM 工件发布到 Artifactory 上的本地 YUM 存储库 我遇到的问题是 发布任务似乎尝试上传工件两次 第二次尝试失败 正确 HTTP 状态代码为 403 我进行
  • n 个素数之和 java,困惑

    我读过几篇关于这方面的文章 我什至在一次考试中这样做过 但是是在 vb net 中 它工作得很好 但是当我尝试执行我的程序时 Eclipse 只是不停地运行 否则它会给我错误的答案 这是我的第四次尝试 我需要将前 n 个素数相加 因此我检查
  • wsimport Xauthfile 错误

    我正在尝试为我们公司网络外部的受 SSL 保护的 Web 服务 在 Microsoft Biztalk 上 生成客户端 也称为消费者 所需的 java 帮助类 我们只能通过代理访问它 并且无法更改 Web 服务本身的任何内容 这是我提供给
  • 在.NET中,Array仅扩展了IEnumerable,那么foreach循环遍历值类型数组时会出现装箱和拆箱吗?

    Array只是扩展了IEnumerable的非泛型版本 那么foreach循环遍历值类型数组时会不会出现装箱和拆箱呢 我猜不会 因为那会很蹩脚 如果我的猜测是正确的 那么 foreach 是如何遍历值类型数组的呢 它不使用Array Get
  • 在jodatime中计算一个月的周数

    jodatime 可以计算一个月的周数吗 我需要这样的东西 月份 七月 第 27 年的一周 1 7 七月 第 28 年的一周 9 14 七月 第 29 年的一周 16 21 七月 第 30 年的一周 23 31 七月 月份 八月 第 31
  • 正则表达式忽略引号之间的文本

    我有一个正则表达式 它是 s 这用于分割字符串 但我不想让它分开 如果它在引号中 我不会使用 split 而是使用 Pattern 和 Matcher A demo import java util regex Matcher import
  • JOOQ初始化DAO最佳方法

    我想知道初始化 JOOQ 生成 DAO 的最佳实践 现在 我使用以下方法来初始化 JOOQ 生成的 DAO 在以下情况下 Student Dao 是 JOOQ 生成的 public class ExtendedStudentDAO exte
  • JTable 使用行号?

    我正在创建一个程序 其工作原理如下Microsoft Excel 在JAVA中 我的问题是如何将行号放在每行旁边JTable 我已经看到它在其他 Java 程序中工作 我只是不知道如何将它包含在我的程序中 谷歌给了我这个网站 http ti
  • Scala - InvalidClassException:没有有效的构造函数

    我创建了一个Serializable番石榴的版本ImmutableRangeMap and Builder在 Scala 中以便在我的 Spark 应用程序中使用 我的构造函数中有一个零参数SerializableImmutableRang
  • 在 R 中将数组转换为矩阵

    我有一个数组 其中包括名为 comp 的项目 是 否 的两个熟练度变量 theta0 theta1 这需要转换为一个矩阵 有什么方法可以转换像底部那样的矩阵吗 我的数组如下所示 gt priCPT i6 comp Yes theta1 th
  • MyBatis 遵循 JPA 吗?

    作为我的第一个 ORM 我已经使用 myBatis 几个月了 现在我正在尝试学习其他东西 例如 Hibernate JPA 起初很难理解 Hibernate 和 JPA 之间的区别 经过几分钟的研究 我明白 JPA 只是一个规范 Hiber
  • Hibernate 过滤器仅在从数据库加载数据后应用吗?

    我在网上发现了一些相互矛盾的信息 有谁知道Hibernate过滤器是否影响生成的sql 或者只是过滤从数据库读取的数据 休眠过滤器影响 where 子句生成的 SQL The Hibernate 过滤器简介 http java dzone
  • 将 person.city.name 添加到 TableView

    我有一个 TableView 和一些 POJO 并且想要将其中一个属性绑定到 TableView 然而 该属性也是一个 POJO 并且应该有一个属性显示在 TableView 中 这是我的代码
  • 在 DAO 中反映继承关系最有效的方法是什么?

    使用 MVC 结构和业务对象 http en wikipedia org wiki Business object DAO http en wikipedia org wiki Data access object建筑学 对于任何正常的业务
  • 如何在类图中对自定义异常关联进行建模?

    Reading here http www jguru com faq view jsp EID 62790 似乎使用泛化来建模自定义异常类很常见 它没有提到的是我如何对与可能引发自定义异常的类的关联进行建模 请注意 我并不是在问如何在引发
  • org.openqa.selenium.remote.service.DriverService$Builder.createArgs()Lcom/google/common/collect/ImmutableList;使用 Selenium 3.5.3

    我正在使用 IntelliJ 编写 Selenium Junit 测试 如果我直接从测试触发 测试运行正常 但是 如果我使用 JunitCore 触发 TestRunnerSuite 的测试 我遇到了以下奇怪的错误 在谷歌研究后我没有找到解
  • Python Blowfish 加密

    由于我对 Java 的了解不完整 我正在努力将此加密代码转换为 Python 代码 两者应该得到完全相同的结果 帮助将不胜感激 Java函数 import javax crypto Cipher import javax crypto sp
  • 异常中的错误代码与异常层次结构

    您认为在异常中使用错误代码来指定错误类型可以吗 请看一下这段代码 public class MyException extends Exception public static final String ERROR CODE INVALI
  • 我可以为每个片段单独提供工具栏吗?如何处理导航抽屉

    在我的应用程序中 某些页面的工具栏中有自定义视图 有些片段具有透明工具栏 有些片段具有坐标布局滚动 因此 我决定为每个片段单独设置工具栏 我想知道这是否是一个好的做法 如果有人已经这样做了 请分享代码或示例 您可以在片段中使用自定义工具栏
  • Java 8 哈希映射无法正常工作

    自 java 8 以来 我们面临着 HashMap 行为方式的奇怪问题 当HashMap的键实现了Comparable接口 但compareTo的实现与equals不一致时 HashMaps 长得比它们应该长的大得多 它们包含多个相同元素的

随机推荐