Can somebody please help me with this Java problem? create and test an updated T
ID: 3596285 • Letter: C
Question
Can somebody please help me with this Java problem?
create and test an updated Trivia class:
The Trivia class has two String instance variables, question and answer.
Define a constructor to initialize a Trivia object’s question and answer.
The Trivia class has only getter methods for these instance variables, so once they have been set by the constructor they can’t be changed.
The Trivia class should also have a toString() method to return its info (its question and answer) as a String.
Write a main method that creates two Trivia objects and then uses each of those objects’ question and answer instance variables (obtained by using their getter methods) to ask the user those two questions, reads their answer for each using nextLine(), and tells them whether they had the right answer in each case.
Use the String equalToIgnoreCase(…) method to check their answer.
Also in main, print the two Trivia objects to show that this automatically runs their toString() methods.
Explanation / Answer
Please find my implementation.
import java.util.Scanner;
public class Trivia {
private String question;
private String answer;
// constructor
public Trivia(String question, String answer) {
super();
this.question = question;
this.answer = answer;
}
// getters
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
@Override
public String toString() {
return "Question: "+question+" "+
"Answer: "+answer;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String Q1 = "what is cow ? ";
String ans1 = "Animal";
String Q2 = "What is Java ? ";
String ans2 = "Language";
System.out.println(Q1);
String ans = sc.nextLine();
Trivia t1 = new Trivia(Q1, ans);
System.out.println(Q2);
ans = sc.nextLine();
sc.close();
Trivia t2 = new Trivia(Q2, ans);
if(t1.getAnswer().equalsIgnoreCase(ans1)) {
System.out.println("Answer 1 is correct");
}else{
System.out.println("Answer for Q1 is incorrect. Correct answer is "+ans1);
}
if(t2.getAnswer().equalsIgnoreCase(ans2)) {
System.out.println("Answer 2 is correct");
}else{
System.out.println("Answer for Q2 is incorrect. Correct answer is "+ans2);
}
}
}
/*
Sample run:
what is cow ?
animal
What is Java ?
bird
Answer 1 is correct
Answer for Q2 is incorrect. Correct answer is Language
*/