我应该添加什么来打印我在driver类中传递的所有问题?

eoxn13cs  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(319)

这是我的问答课。

class Question{
    String question, answer;
    Question()
    {
        question = null;
        answer = null;
    }

    public Question(String question, String answer)
    {
        this.question = question;
        this.answer = answer;
    }

    public String toString(){
        return question;
    }
}

class Quiz extends Question{
    String name;

    Quiz(String name)
    {
        super();
        this.name = name;
    }

    public void addQuestion(Question q)
    {
        answer = q.answer;
        question = q.question;
    }

    public String toString(){
        return name+"\n\n" + question;
    }
}

这是我的驾驶课。

public class QuizSample{
    public static void main(String[] args){
        Quiz sample = new Quiz("Sample 1903 Quiz");

        sample.addQuestion(new Question("Who is known as the father of Java?", "James Gosling"));
        sample.addQuestion(new Question("Write a statement that assigns the length of a string s to int i", "i = s.length();"));
        sample.addQuestion(new Question("True or false: assigning an int to double is an example of a widening conversion", "true"));

        System.out.println(sample);
    }
}

这是输出:
1903测验示例
true或false:将int赋值给double是一个加宽转换的示例
但是我想把我通过的所有问题都打印出来。请帮帮大家。

3lxsmp7m

3lxsmp7m1#

你的测验课可以有一个列表来存储所有的问题,
喜欢

List<Questions> lstQuestions = new ArrayList<Questions>();

并且可以在addquestion方法中添加所有问题,

public void addQuestion(Question q)
    {
        lstQuestions.add(q);
    }

主要方法如下所示,

public static void main(String[] args) {

        Scanner console = new Scanner(System.in);
        System.out.println("Welcome to my Quiz");

        for(Question quest : lstQuestion){
            System.out.println(quest);
            String ans = console.next();
            if(quest.getAnswer().equals(ans.trim())){
                System.out.println("right answer");
            }else{
                System.out.println("wrong answer");
            }

        }
        console.close();

    }
gkl3eglg

gkl3eglg2#

班级 Quiz 不需要扩展 Question 而是有一个问题的集合(列表或集合)。
也, toString 方法需要更新为漂亮的打印问题。

import java.util.*;
import java.util.stream.*;

class Quiz {
    String name;
    List<Question> questions = new ArrayList<>();

    Quiz(String name) {
        this.name = name;
    }

    public void addQuestion(Question q) {
        questions.add(q);
    }

    public String toString() {
        return name+"\n\n" + questions.stream()
                                      .map(Question::toString)
                                      .collect(Collectors.joining("\n"));
    }
}

相关问题