jane doe jane doe - 23 days ago 5
Java Question

how to insure nothing is asked twice in array?

I have an assignment where I have to create a quiz on the USA capitals. I have to read from an input file and store the state name and capital data into an array. Then I have to ask the user what the capital of ___ is. It randomly pulls the state names from the array.

I have the quiz completely done but am having trouble with one requirement. How do I ensure that no question is asked twice?
For example, for each run of the program, if the user has been asked what the capital of Ohio is, it should never ask about Ohio again.

If questions about all states are asked, the program should automatically present the quiz results and terminate. How do I do this? Thank you for your help.

Everything works correctly I just need to add this one requirement to it. I have a total of three classes but I only gave you the class that sets the quiz up itself:

public void takeQuiz() throws FileNotFoundException
{
Scanner check = new Scanner(System.in);

int runThrough = 0;
int count = 0;
double right = 0.0;
String next = "";
Random rand = new Random();
Collections.shuffle(list);
int ques = 0;

while (runThrough == 0 && ques < 50)
{ System.out.print("What's the capital of " + list.get(ques).getName()
+ "? (STOP to quit) ");

if (next.equals("STOP"))
{
runThrough++;
}
else
{
if (next.equals(list.get(ques).getCapital()))
{
System.out.println("Right!");
right++;
count++;
}
else
{
System.out.println("No, the answer is "
+ list.get(ques).getCapital());
count++;
}
}

++ques;
}

Answer

Here's the easiest way to do it. Keep in mind that because no question can be repeated, at max 50 questions can be asked.

Random rand = new Random();
Collections.shuffle(list);

int ques = 0;
while (runThrough == 0 && ques < 50) {
    System.out.print("What's the capital of " + list.get(ques).getName()
        + "? (STOP to quit) ");

    // Your other stuff remains as is, just update
    // list.get(ques).getCapital()
    //           ^^

    ++ques;
}

You also need to import java.util.*;.

Explaination: Shuffle your questions list, then ask these questions in the new order.

Comments