▪ ▪
using java
Create a FOR loop to go over all the questions, one by
one.
For each question:
o Create a String variable and concatenate the questions and the
multiple choices.
o To have new lines as shown in the figure above, concatenate “\n”
after each possible answer in the multiple
choice.
Collect the answer from the JOptionPane dialog box (you will need to convert the returning value from String to integer).
▪ Compare this value with the actual correct answer that you got from the text file (the integer array of correct answers that you have created.
▪ Create an integer variable to keep track of how many answers were correct.
o Use this concatenated string as input in your JOptionPane.showInputDialog() method.
/**
* Java program that display a questions and prompts user
* to enter the user response and then find the number of
* correct answers .Then display the number of correct answers
* in a message dialog box.
* */
//MultipleChoice.java
import java.io.File;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class MultipleChoice
{
public static void main(String[] args)
{
int correct=0;
//questions
String q1="What is capital of
USA?\n1.Washington\n2.NewYork\n3.Texas";
String q2="What is capital of
INDIA?\n1.Hyderabad\n2.New Delhi\n3.Mubmbai";
String q3="What is capital of
SriLanka?\n1.Columbo\n2.China\n3.koria";
//create an array of
questions
String questions[]=
{q1,q2,q3};
final int size=3;
//an array of integer data
type
int[]answers=new int[size];
String
fileName="answers.txt";
Scanner filereader=null;
int index=0;
try
{
//open file for
reading
filereader=new
Scanner(new File(fileName));
while(filereader.hasNext())
{
//read answers from file
answers[index]=Integer.parseInt(filereader.next());
index++;
}
filereader.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
int user_response;
for (int i = 0; i <
answers.length; i++)
{
//prompt for the
user response
user_response=Integer.parseInt(JOptionPane.showInputDialog(null,
questions[i]));
//check if
answer is correct
if(user_response==answers[i])
correct++;
}
//show number of correct answers
count
JOptionPane.showMessageDialog(null,"The number of correct answers
are "+correct);
}
}
------------------------------------------------------------------------------------------------------------------------------------------------
answers.txt
1 2 1
------------------------------------------------------------------------------------------------------------------------------------------------
Sample Output:




▪ ▪ using java Create a FOR loop to go over all the questions, one by...