Stack Overflow Asked by Suvab on December 12, 2020
These are my quiz and question class.
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+"nn" + question;
}
}
And this is my driver class.
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);
}
}
This is the output:
Sample 1903 Quiz
True or false: assigning an int to double is an example of a widening conversion
But I want to print all the questions that I have passed.
Please help guys.
Your Quiz class can have a List to store all the questions,
like
List<Questions> lstQuestions = new ArrayList<Questions>();
and can be used in addQuestion method to add all the questions,
public void addQuestion(Question q)
{
lstQuestions.add(q);
}
and the main method can look like below,
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();
}
Answered by Prabhu on December 12, 2020
Class Quiz
does not need to extend Question
but rather to have a collection of questions (list or set).
Also, toString
method needs to be updated to pretty print questions.
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+"nn" + questions.stream()
.map(Question::toString)
.collect(Collectors.joining("n"));
}
}
Answered by Alex Rudenko on December 12, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP