This site requires JavaScript, please enable it in your browser!
Greenfoot back
arm0123
arm0123 wrote ...

2019/11/7

How do I have a prompt appear after a certain amount of time?

arm0123 arm0123

2019/11/7

#
I need to have a Greenfoot.ask() prompt appear after 5 seconds and then go away after the answer is inputted. However, I can't get my timer to work and it won't disappear after answer has been inputted. public class Calculations extends Actor { String questions = {"5/9 times 1/2", "2/3 times 5/7", "1/2 times 1/3", "5/7 times 7/5", "3/4 times 1/4", "1/4 times 1/3", "7/8 times 1/2", "1/4 times 1/4", "1/2 times 1/2", "3/2 times 1/2", "1/7 times 2/3", "1/8 times 1/2", "1/3 times 1/3", "1/5 times 1/5", "1/2 times 1/6", "1/2 times 1/4"}; String answers = {"5/18", "10/21", "1/6", "1", "3/16", "1/12", "7/16", "1/16", "1/4", "3/4", "2/21", "1/16", "1/9", "1/25", "1/12", "1/8"}; int count; /** * Act - do whatever the Calculations wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { int Timer = 6; if (Timer > 0) { Timer--; } else if (Timer == 0) { Prompt(); } } private void Prompt() { int index = (int)(Math.random() * 16); String ianswer = Greenfoot.ask("Question: " + questions); if (ianswer == answers) { Greenfoot.start(); count++; //correct } else { //fail } } }
danpost danpost

2019/11/7

#
As coded, once the timer reaches zero, the ask is executed -- continuously. Change the act method to this:
public void act()
{
    if (Timer > 0)
    {
        Timer--;
        if (Timer == 0) Prompt();
    }
}
or equivalently
public void act()
{
    if (Timer > 0 && --Timer == 0) Prompt();
}
The following line should be outside the method so the value can be retained by the actor:
int Timer = 300;
danpost danpost

2019/11/7

#
arm0123 wrote...
if (ianswer == answers[index])
{
     Greenfoot.start();
     count++;  //correct
}
else  {  }  //fail
With this part of your code, line 1 will not ever be true. The two String object are not the same object, regardless of the contents of the strings. Use the following to compare their contents:
if (answer[index].equals(ianswer))
I cannot see any reason to have line 3 in this part of your code as the scenario would already be in a running state.
You need to login to post a reply.