153k views
3 votes
Create a Flash Card class. Flash Cards have a Question and an Answer, each of which are Strings. Your class should include a constructor, toString() and equals() methods. Write a main() method that creates an array of three Flash Cards, and prints each of them.

User Orftz
by
5.9k points

1 Answer

0 votes

Answer:

FlashCard.java

  1. public class FlashCard {
  2. String Question;
  3. String Answer;
  4. public FlashCard(String q, String a){
  5. this.Question = q;
  6. this.Answer = a;
  7. }
  8. public String toString(){
  9. String output = "";
  10. output += "Question: " + this.Question + "\\";
  11. output += "Answer: " + this.Answer;
  12. return output;
  13. }
  14. public boolean equals(String response){
  15. if(this.Answer.equals(response)){
  16. return true;
  17. }
  18. else{
  19. return false;
  20. }
  21. }
  22. }

Main.java

  1. public class Main {
  2. public static void main(String[] args) {
  3. FlashCard card1 = new FlashCard("What is highest mountain?", "Everest");
  4. FlashCard card2 = new FlashCard("What is natural satelite of earth?", "Moon");
  5. FlashCard card3 = new FlashCard("Who is the first president of US?", "George Washington");
  6. FlashCard cards [] = {card1, card2, card3};
  7. for(int i=0; i < cards.length; i++){
  8. System.out.println(cards[i]);
  9. }
  10. }
  11. }

Step-by-step explanation:

In FlashCard.java, we create a FlashCard class with two instance variable, Question and Answer (Line 2 - 3). There is a constructor that takes two input strings to initialize the Question and Answer instance variables (Line 5-8). There is also a toString method that will return the predefined output string of question answer (Line 10 - 15). And also another equals method that will take an input string and check against with the Answer using string equals method. If matched, return True (Line 17 -24).

In Main.java, create three FlashCard object (Line 3-5) and then put them into an array (Line 6). Use a for loop to print the object (Line 8-10). The sample output is as follows:

Question: What is highest mountain?

Answer: Everest

Question: What is natural satelite of earth?

Answer: Moon

Question: Who is the first president of US?

Answer: George Washington

User Freya
by
5.5k points