Create a text file called “Trivia.txt” that contains the contents of a trivia game, where the questions and answers are on separate lines. Example:
How many players are on a Baseball team?
Nine
What is the name of Batmans butler?
Alfred
Hg is the chemical symbol for what element?
Mercury
Create a program that reads the trivia questions from this text file, prints them out to netbeans and asks the user to input an answer. Compare the users answer to the correct answer on your text file. Provide an appropriate output letting the user know if they are correct, or if they are wrong what the correct answer should be.
Please help me code this in Java.
Code:
package demos;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class demo49 {
public static void main(String args[]) {
ArrayList<String> questions =
new ArrayList<String>();
ArrayList<String> answers =
new ArrayList<String>();
int i=0;
try {
File myObj = new
File("C:\\Users\\Anurag\\eclipse-workspace\\demos\\src\\demos\\Trivia.txt");
Scanner myReader = new
Scanner(myObj);
while (myReader.hasNextLine())
{
String data =
myReader.nextLine();
if(i%2==0)
questions.add(data);
else
answers.add(data);
i++;
}
myReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error
occurred.");
e.printStackTrace();
}
Iterator<String> iterQues =
questions.iterator();
Iterator<String> iterAns =
answers.iterator();
Scanner sc = new
Scanner(System.in);
while(iterQues.hasNext() &&
iterAns.hasNext()) {
String question
= iterQues.next(), answer = iterAns.next();
System.out.println(question);
System.out.print("Ans: ");
String givenAns
= sc.nextLine();
if(answer.equalsIgnoreCase(givenAns))
System.out.println("Correct Answer.");
else
System.out.println("Wrong, the correct ans is:
"+answer);
}
sc.close();
}
}
Note: change the file location to where your file is.
Output:
Hope this helps.
Get Answers For Free
Most questions answered within 1 hours.