Java 我应该添加什么来打印我在driver课程中通过的所有问题?
这是我的问答课Java 我应该添加什么来打印我在driver课程中通过的所有问题?,java,object,tostring,Java,Object,Tostring,这是我的问答课 class Question{ String question, answer; Question() { question = null; answer = null; } public Question(String question, String answer) { this.question = question; this.answer = ans
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是加宽转换的一个示例 但我想打印我通过的所有问题。
请帮助大家。课堂
测验
不需要扩展问题
,而是需要一系列问题(列表或集合)
另外,toString
方法需要更新,以便打印出漂亮的问题
import java.util.*;
导入java.util.stream.*;
课堂测验{
字符串名;
列出问题=新建ArrayList();
测验(字符串名称){
this.name=名称;
}
公众提问(问题q){
问题.添加(q);
}
公共字符串toString(){
返回名称+“\n\n”+问题。流()
.map(问题::toString)
.collect(收集器.加入(“\n”));
}
}
您的测验课可以有一个列表来存储所有问题
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();
}
您的类无法处理此问题,无论何时使用
addQuestion()
它都会删除sample
中存储的旧值。尝试使用列表存储问题,并将其打印出来。制作测验
,因为问题
的扩展类不能解决问题。相反,测验
应该包含问题列表
,这里测验不是一个问题,而是一组问题。你需要重构你的代码。您应该为是一个
关系使用继承。您可以使用字符串数组来存储用户提供的所有答案。然后迭代每个问题,并根据与测验课答案值的比较来检查是否正确,并相应地打印问题。
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();
}