简体   繁体   中英

How do i stop a random number generator in my app without making the app to freeze

My app uses a Random Number Generator to display random questions to the users but there is just one problem, this random numbers doesn't stop and will always generate a number which will show a different question always.

So i tried to stop that using a while and an if loop, after i wrote that, i notice that the app keep freezing.

what are the best ways to stop this Random number generator without freezing the app.

package com.myafrica.africaquiz;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Random;


public class MainActivity extends AppCompatActivity {

//this variable stores the total number of correct answers
int StoresTotalCorrectAnswer;

//this variable count the total number of RandomQuestions asked
int RandomNumberCounter;

//this variable stores the random numbers generated
int RandomNumber;

//variables of the views for public access to other classes
TextView TestQuestionID = null;
RadioButton AnswerA_ID = null;
RadioButton AnswerB_ID = null;
RadioButton AnswerC_ID = null;
RadioButton AnswerD_ID = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //get the text view and stores it in this variable
    TestQuestionID = findViewById(R.id.TestQuestion);

    //get the radio button view and stores it in this variable
    AnswerA_ID = findViewById(R.id.AnswerA);
    AnswerB_ID = findViewById(R.id.AnswerB);
    AnswerC_ID = findViewById(R.id.AnswerC);
    AnswerD_ID = findViewById(R.id.AnswerD);
}

//When the onclicked() is clicked this method runs
public void GetNextQuestion(View view) {
    RandomNumberGenerator();
}

//Creating a random number generator
public void RandomNumberGenerator() {

    Random RanNum = new Random();
    RandomNumber = RanNum.nextInt(4) + 1;

    //to know how many times the random method has been called
    while (RandomNumber >= 0) {
        RandomNumberCounter++;

        //to stop the questions from displaying once the required number is 
 //reached
        if (RandomNumberCounter < 4) {

            switch (RandomNumber) {

                case 1:
                    Question1();
                    break;

                case 2:
                    Question2();
                    break;

                case 3:
                    Question3();
                    break;

                case 4:
                    Question4();
                    break;
            }

            // not done with this part yet, but was trying to store the 
 //correct answers
            if (RandomNumber == 1 && AnswerA_ID.isChecked()) {
                StoresTotalCorrectAnswer++;
            } else if (RandomNumber == 2 && AnswerA_ID.isChecked()) {
                StoresTotalCorrectAnswer++;
            } else if (RandomNumber == 3 && AnswerD_ID.isChecked()) {
                StoresTotalCorrectAnswer++;
            } else if (RandomNumber == 4 && AnswerA_ID.isChecked()) {
                StoresTotalCorrectAnswer++;
            }
        }

        // shows a different layout after the question stops showing
        else {
            Intent i = new Intent(this, Main2Activity.class);
            startActivity(i);
        }
    }
}


 /*
    This part of the code will contain the answer part of this quiz app.
    Each question is a method and that method will be called when the Next 
button is clicked in the app.
    When the button is clicked the setText() will automatically (re)set the 
text in the question layout in the XML
     */
public void Question1() {
    TestQuestionID.setText("Which part of Africa can Ghana be located");
    AnswerA_ID.setText(" A: West Africa");
    AnswerB_ID.setText(" B: East Africa");
    AnswerC_ID.setText(" C: Central Africa");
    AnswerD_ID.setText(" D: North Africa");
}

public void Question2() {
    TestQuestionID.setText("What is the capital of Nigeria");
    AnswerA_ID.setText(" A: Abuja");
    AnswerB_ID.setText(" B: Kano");
    AnswerC_ID.setText(" C: Lagos");
    AnswerD_ID.setText(" D: Port Harourt");
}

public void Question3() {
    TestQuestionID.setText("Which of these countries are not located in 
Africa");
    AnswerA_ID.setText(" A: Niger");
    AnswerB_ID.setText(" B: Nigeria");
    AnswerC_ID.setText(" C: Rwanda");
    AnswerD_ID.setText(" D: Non of the Above");
}

public void Question4() {
    TestQuestionID.setText("What is the estimated population of Africa, as at 
 2015");
    AnswerA_ID.setText(" A: 1.2 Billion");
    AnswerB_ID.setText(" B: 500 Billion");
    AnswerC_ID.setText(" C: 2 Billion");
    AnswerD_ID.setText(" D: 360 million");
}
}

i tired to make the comments on the code understandable, so anyone can understand what each section of the code will do.

NOTE: what i really need is a way to stop the random number generator which always bring about a random question after X times and displays a different layout which will show the total number of questions answered

Your while loop does not reach exit condition, that is why it is doing work indefinitely. What you should do is break out of the loop when you reach desirable condition. For example in your else statement where you start new Activity , you should put break; at the end:

...    

int RandomNumberCounter = 0;     // you have to assign a sum variable to be 0 or else it stores random value.

...

while (RandomNumber >= 0) {
    RandomNumberCounter++;

    if (RandomNumberCounter < 4) {
        ...
    }
    else {   
        Intent i = new Intent(this, Main2Activity.class);
        startActivity(i);
        break;               // this breaks execution of your while loop
    }
}

Good luck :)

Overview

Yes, you have some formatting issues with your code but I am going to go out on a limb here and assume you've started out recently because you've got an issue here that is fairly obvious.

The simple answer to your question is: You can't. What you want to do isn't possible. What you have created here is an infinite loop!

Here is what is happening:

You create a while loop and tell that loop: "Please continue repeating as long as the value of the variable 'randomNumbers' is greater than 0"

Inside of the loop, you are incrementing the value of 'randomNumbers' by 1 every time the while loop repeats.

What this means is that there's never a reason for your while loop to stop repeating! Luckily, this is an easy fix. All we need to do is change what will make the while loop stop repeating.

Current while loop condition:

randomNumbers >= 0

Think about it like this: "When do I want my while loop to stop repeating? What am I counting?"

The answers to those questions will form what you need to change the while loop's condition to. I believe, the answer you need, is to change the while loop condition to this:

while(randomNumbers is <= howManyQuestionsIWant)

That will definitely solve your while loop repeating issue. Only quickly glancing at the rest of the code, there be other bugs in there but this will at least get you past the repeating loop of doom problem so you can start debugging the rest. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM