'Multiple Choice Java Quiz : How to input questions from a text file?
I'm creating a multiple choice quiz using Java. I have the actual program up and running with all 10 of the questions when they're hard coded into the source code but I need to place 7 of these questions into a text file that will be inputted from a .txt and answered just the same. The only difference of course being those 7 questions that come from a text file instead of being directly in the source code.
Can someone explain or show me a way to get this text file to be inputted into my source code and the quiz up and running this way?
Here is my overall source code:
import java.util.Scanner;
import java.util.*;
String q1 = "What is hardware?\n"
+ "(a)virtual machine\n(b)the physical machine\n(c)applications such as browsers\n(d)part of the processor\n";
String q2 = "What does counter++; do?\n"
+ "(a)Adds 1 to counter\n(b)Adds 2 to counter\n(c)Gets the sum\n(d)Multiplies the numbers\n";
String q3 = "What is a loop that never stops?\n"
+ "(a)For Loop\n(b)Infinite Loop\n(c)Do-While Loop\n(d)Full Loop\n";
Question [] questions = {
new Question(q1, "b"),
new Question(q2, "a"),
new Question(q3, "b"),
new Question(q4, "c"),
new Question(q5, "d"),
new Question(q6, "a"),
new Question(q7, "a"),
new Question(q8, "c"),
new Question(q9, "a"),
new Question(qF, "c")
};
Collections.shuffle(Arrays.asList(questions));
takeTest(questions);
}
public static void takeTest(Question [] questions){
int score = 0;
Scanner keyboardInput = new Scanner(System.in);
for(int i = 0; i < questions.length; i++) {
System.out.println(questions[i].prompt);
String answer = keyboardInput.nextLine();
if(answer.equals(questions[i].answer)) {
score++;
}
}
System.out.println("You got " + score + "/" + questions.length);
}
}
And my text file is simply the seven questions that I had originally placed in the source code :
String q4 = "In a while loop, if the boolean expression is true, what will the loop do?\n"
+ "(a)Break\n(b)Program will exit\n(c)Repeat\n(d)Continue through program\n";
String q5 = "What special value is designated for controlling a loop?\n"
+ "(a)Control value\n(b)Mutator Method\n(c)Accessor Method\n(d)Sentinel Value\n";
String q6 = "What is a method?\n"
+ "(a)A collection of statements grouped together to perform an operation\n(b)A value returned from a method using the return statement\n(c)The portion of the program where the variable can be accessed.\n(d)The combination of the name of a method and the list of its parameters\n";
String q7 = "What is an object?\n"
+ "(a)Representation of an entity in the real world that can be distinctly identified\n(b)A static method can be called without creating an instance of the class\n(c)Instance variable/instance mthod\n(d)A template, blueprint or contract that defines what an object's data fields and methods will be.\n";
String q8 = "What is an array?\n"
+ "(a)Numbers of items ArrayList can store without increasing its size\n(b)Number used as an index to pinpoint a specfic element within an array\n(c)Object that can store a group of values, all of the same type\n(d)Method of locating a specific item in a larger collection of data\n";
String q9 = "You use this statement to throw an exception manually.\n"
+ "(a)Throw\n(b)call stack\n(c)try block\n(d)thrown\n";
String qF = "When an exception is generated, it is said to have been what?\n"
+ "(a)Created\n(b)Called\n(c)Thrown\n(d)Generated\n";
Solution 1:[1]
You can use BufferedReader and try to read line by line.
Here an example of using BufferedReader:
BufferedReader br = new BufferedReader(new FileReader("PATH TO QUESTIONS FILE"));
String read = "";
while((read = br.readLine()) != null){
System.out.println(read);
}
Doing that you will read and print each line of a File.
Make sure you will write each question in a line, otherwise questions will be mixed.
Hope I helped you. :)
Solution 2:[2]
I have used Dynamic memory allocation approach for this using ArrayList.
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> que = new ArrayList<>();
que.add("What is java");
que.add("What is python");
que.add("What is C");
que.add("What is C++");
ArrayList<String> opt = new ArrayList<>();
opt.add("PL,SL,Both,None");
opt.add("SL,PL,Both,None");
opt.add("PL,None,SL,Both");
opt.add("PL,Both,None,SL");
ArrayList<String> correct = new ArrayList<>();
correct.add("PL");
correct.add("Both");
correct.add("PL");
correct.add("PL");
Scanner sc = new Scanner(System.in);
String c1="";
int count=0;
for(int i=0;i<que.size();i++)
{
String q=que.get(i);
System.out.println(q);
String o=opt.get(i);
{
String[] s1 = o.split(",");
for(String s:s1)
{
System.out.println(s);
}
}
String c=correct.get(i);
{
c1 = c;
}
System.out.println("Your option: ");
String yr = sc.nextLine();
if(yr.equalsIgnoreCase(c1))
{
count++;
}
}
System.out.println("Marks:"+count);
}
}
Solution 3:[3]
import java.lang.System;
import java.lang.String;
import java.io.*;
import java.util.Scanner;
class Que_6
{
public static void main(String Args[]) throws IOException
{
String username ="";
String password ="";
String ans1,ans2,ans3,ans4,ans5,ans6,ans7,ans8,ans9,ans10;
char choice;
int i=0;
int x=0;
do
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner s = new Scanner(System.in);
System.out.println("1. USER");
System.out.println("2. ADMIN");
System.out.println("3. EXIT!");
System.out.print("Enter Your Choice: ");
x = Integer.parseInt(br.readLine());
switch(x)
{
case 1:
System.out.print("USER");
System.out.print("\nUsername: ");
username = br.readLine();
System.out.print("Password: ");
password = br.readLine();
break;
case 2:
System.out.println("ADMIN");
break;
case 3:
System.out.println("EXIT!");
System.exit(0);
default:
System.out.println("Invalid Choice!");
}
System.out.println("\n1. Number of primitive data type in Java?");
System.out.println("\nA. 6 \nB. 7 \nC. 8 \nD. 9");
do
{
System.out.print("\nAns: ");
ans1 = br.readLine();
}while(ans1 == "C");
if(ans1 == "A" || ans1 == "B" || ans1 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n2. What's the size of float and double in Java?");
System.out.println("\nA. 32 and 64 \nB. 32 and 32 \nC. 64 and 64 \nD. 64 and 32");
do
{
System.out.print("\nAns: ");
ans2 = br.readLine();
}while(ans2 == "B");
if(ans2 == "A" || ans2 == "C" || ans2 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n3. Select the valid Statement...");
System.out.println("\nA. char[] ch = new char(5) \nB. char[] ch = new char[5] \nC. char[] ch = new char() \nD. char[] ch = new char[]");
do
{
System.out.print("\nAns: ");
ans3 = br.readLine();
}while(ans3 == "A");
if(ans3 == "B" || ans3 == "C" || ans3 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n4. Array in Java are-");
System.out.println("\nA. Objects \nB. Object Refrences \nC. Primitive Datatypes \nD. None");
do
{
System.out.print("\nAns: ");
ans4 = br.readLine();
}while(ans4 == "A");
if(ans4 == "B" || ans4 == "C" || ans4 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n5. What is the object created with new keyword?");
System.out.println("\nA. At run time \nB. At compile time \nC. Depends on code \nD. None");
do
{
System.out.print("\nAns: ");
ans5 = br.readLine();
}while(ans5 == "A");
if(ans5 == "B" || ans5 == "C" || ans5 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n6. In which of the following is toString() method defined?");
System.out.println("\nA. java.lang.object \nB. java.lang.String \nC. java.lang.util \nD. None");
do
{
System.out.print("\nAns: ");
ans6 = br.readLine();
}while(ans6 == "A");
if(ans6 == "B" || ans6 == "C" || ans6 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n7. compareTo() returns-");
System.out.println("\nA. True Value \nB. False Value \nC. An int Value \nD. No Value return");
do
{
System.out.print("\nAns: ");
ans7 = br.readLine();
}while(ans7 == "C");
if(ans7 == "A" || ans7 == "B" || ans7 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n8. To which of the following does the class string belong to...?");
System.out.println("\nA. java.lang \nB. java.awt \nC. java.applet \nD. java.String");
do
{
System.out.print("\nAns: ");
ans8 = br.readLine();
}while(ans8 == "A");
if(ans8 == "B" || ans8 == "C" || ans8 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n9. Total constructor string class have?");
System.out.println("\nA. 3 \nB. 7 \nC. 13 \nD. 20");
do
{
System.out.print("\nAns: ");
ans9 = br.readLine();
}while(ans9 == "C");
if(ans9 == "A" || ans9 == "B" || ans9 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("\n10. Output of Math.floor(3.6)?");
System.out.println("\nA. 3 \nB. 3.0 \nC. 4 \nD. 4.0");
do
{
System.out.print("\nAns: ");
ans10 = br.readLine();
}while(ans10 == "B");
if(ans10 == "A" || ans10 == "C" || ans10 == "D")
{
System.out.println("Incorrect Answer!");
}
System.out.println("1. "+ans1+"\n2. "+ans2+"\n3. "+ans3+"\n4. "+ans4+"\n5. "+ans5+"\n6. "+ans6+"\n7. "+ans7+"\n8. "+ans8+"\n9. "+ans9+"\n10. "+ans10);
System.out.print("\nDo You Want To Continue For Next User Give Test!(Y/N): ");
choice = s.next().charAt(0);
}while(choice == 'Y'|| choice == 'y');
if(choice == 'N'||choice == 'n')
System.out.println("The End!");
}
}
//Ans: C A B A A A C A C B
Solution 4:[4]
- Problem: Grading Multiple-Choice Test
import java.util.Scanner;
public class twoDimentionalArrays {
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
String[] answers = { "D","B","D","C","C","D","A","E","A","D"};
String[][] list = new String[8][10];
System.out.println("Fill in the eight student's answers to 10 questions" );
for (int i =0;i<list.length;i++) {
int count =0;
for (int j=0;j<list[i].length;j++) {
list[i][j] = scan.next();
if(list[i][j].equalsIgnoreCase(answers[j])) count++;
}
System.out.println("Student's " + i + " correct answers are " + count);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Almir Neto |
| Solution 2 | Anupam Haldkar |
| Solution 3 | NHP |
| Solution 4 | Karthikeyan |
