Home > other >  How to break out of 2nd loop(nested) and continue looping
How to break out of 2nd loop(nested) and continue looping

Time:03-10

please I need help with my Java program. I am a beginner so it's really confusing for me. I am trying to build a multiple Question Trivia program. Whereby a user is prompted with a question and they have to choose from the given answers. If they get it right or wrong they are told, and also shown the time they took to answer the question. Now the problem is after they submit their answer to a question, they would be prompted if they want to play again and another question would come up. I have 2 lists 1 for questions ad 1 for answers I am iterating through the two lists with 2 for loops simultaneously so I am able to check if their input is the same as the answer for that question. I am stuck on getting out of the second loop so I can proceed with other questions, I have tried breaking the loop but it breaks and doesn't prompt the user for their answer. How can I solve this please. Here is my code Below, the main program starts at the for-loop

package javaapplication19;

import java.util.Scanner;
import java.util.ArrayList;
import java.time.Duration;
import java.time.Instant;

public class trivia {
    public static <string> void main(String[] args) {

        ArrayList<String> question = new ArrayList<String>();

        question.add(
                "\n\n1. The highest mountain of the world is in which two countries \n\tA. India and Pakistan  \n\tB. China and Tibet \n\tC. Tibet and Nepal \n\tD. Pakistan and Nepal \n\tE. Tanzania and India");
        question.add(
                "The lowest point of land on earth is on the border between which two countries? \n\tA. Mexico and the U.S  \n\tB. Holland and Belgium \n\tC. Israel and Jordan \n\tD. Denmark and Germany \n\tE. Sweden and Tunisia");
        question.add(
                "Where is the biggest desert on earth \n\tA. Siberia  \n\tB. Antartica \n\tC. Africa \n\tD. California \n\tE. Pakistan ");
        question.add(
                "Which capital city in the world is at the highest altitude? \n\tA. Bern, Switzerland  \n\tB. Katmandu, Nepal \n\tC. Ulaanbaatar, Mongolia \n\tD. La Paz, Bolivia \n\tE. Lagos, Nigeria");
        question.add(
                "Which continent has the fewest people leiving in it? \n\tA. Africa  \n\tB. Asia\n\tC. Australia \n\tD. Antartica \n\tE. South America");
        question.add(
                "Which continent has the largest people living on it? \n\tA. Africa  \n\tB. Asia \n\tC. Australia \n\tD. Antartica \n\tE. North America");
        question.add(
                "Which continent has the most countries \n\tA. North America  \n\tB. Asia \n\tC. Antartica \n\tD. Australia \n\tE. Africa");
        question.add(
                "Which country is the biggest in Land area \n\tA. Russia  \n\tB. China \n\tC. Canada \n\tD. The United States \n\tE. India");
        question.add(
                "Which ocean does not border North America \n\tA. Pacific  \n\tB. Atlantic \n\tC. Artic \n\tD. Indian \n\tE. Southern");
        question.add(
                "Which country is the densest in population? \n\tA. Monaco  \n\tB. Singapore \n\tC. China \n\tD. Bahrain \n\tE. Mongolia");

        ArrayList<String> answer = new ArrayList<String>();

        answer.add("C");
        answer.add("C");
        answer.add("B");
        answer.add("D");
        answer.add("D");
        answer.add("B");
        answer.add("E");
        answer.add("A");
        answer.add("D");
        answer.add("A");

        System.out.print(
                "Hey there welcome to the Trivia game, here are the rules and Instructions of the game: \n\n\t1. When you run the game, you would be prompted with a question and 5 answer choice, of which 1 is just true. \n\t2. You are to pick just one answer. \n\t3. To submit your answer you press enter. \n\t4. After submitting your answer you would be promted if you want to play again");

        Scanner sc = new Scanner(System.in);

//Main start of the program
        for (int i = 0; i < question.size(); i  ) {
            System.out.print(question.get(i));

            for (int j = 0; j < answer.size(); j  ) {
                System.out.print("\n");

                long starttime = System.nanoTime();
                String useranswer = sc.nextLine();
                long endtime = System.nanoTime();
                long Duration = endtime - starttime;
                // converting nanoseconds to seconds
                // 1 Second = 1000000000 Nanosecond
                double seconds = (double) Duration / 1000000000;

                if (!answer.get(j).equals(useranswer)) {
                    System.out.println("Aww you got the question wrong :( ");
                    System.out.println("You also took "   seconds   "secs to answer the question");

                    System.out.println("Would you like to play again (yes/no): ");
                    String userinput = sc.next();
                    String input = userinput.toLowerCase();
                    String Validanswer = "yes";

                    if (input.equals(Validanswer)) {
                        System.out.println("\n");
                         break;                     //Where the problem occurs
                    }

                    else {
                        System.out.println("Thanks for playing, see you !");
                        System.exit(j);
                        sc.close();
                    }

                }

                else if (answer.get(j).equals(useranswer)) {
                    System.out.println("You got the Question Right!!");
                    System.out.println("You also took "   seconds   "secs to answer the question");

                    System.out.println("Would you like to play again (yes/no): ");
                    String userinput = sc.next();
                    String input = userinput.toLowerCase();
                    String Validanswer = "yes";

                    if (input.equals(Validanswer)) {
                        System.out.println("\n");
                       break;                        //Also where the problem occurs
                    }

                    else {
                        System.out.println("Thanks for playing, see you !");

                        System.exit(j);
                        sc.close();
                    }
                }
        

            }

        }
    }
}

CodePudding user response:

Consider the following code. I have removed the timers for simplicity, and have converted it into a simple loop without any repeat code. Try running this yourself and note the changes from your code:

//Main start of the program
for (int i = 0; i < question.size(); i  ) {
    //Ask the question
    System.out.println(question.get(i));

    //Get the answer
    String useranswer = sc.nextLine();
    
    //Check the result (note we only need if/else, not if/else if)
    if (!answer.get(i).equals(useranswer)) {
        System.out.println("Aww you got the question wrong :( ");
    }
    else {
        System.out.println("You got the Question Right!!");
    }
    
    //Check if the user wants to keep playing:
    System.out.println("Would you like to keep playing (yes/no): ");
    String userinput = sc.nextLine().toLowerCase();

    //Exit if the user does not type "yes", or just let the loop finish and restart
    if (!input.equals("yes")) {
        System.out.println("Thanks for playing, see you !");
        System.exit(0);
    }
}

As we can see, this is done with a single loop. If the user enters yes to keep playing after answering the question, then the loop simply repeats and prints the next question System.out.println(question.get(i));, so if the user answers no, it simply prints the message and exits.

  • Related