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

2016/10/29

How to get letter input from Greenfoot.ask

AuroraGamer AuroraGamer

2016/10/29

#
If a player loses at any time in the game, I would like to ask them wether or not they would like to play again by entering the letter y or n, but I'm not completely sure how to use Greenfoot.ask to do this. So any help would be appreciated.
danpost danpost

2016/10/30

#
AuroraGamer wrote...
I would like to ask them wether or not they would like to play again by entering the letter y or n, but I'm not completely sure how to use Greenfoot.ask to do this.
Using 'ask' here might not be the most appropriate way to go about asking for a single character String input; but here we go. Since 'ask' returns a String object, there are two things that you should check for -- a length of one and whether the character is in the String "YyNn". As long as both are not satisfied, the question must be 'ask'ed again (using a while loop). You may even want to add "Invalid input -- please try again." to the question text. This would look something like the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
String prompt = "Would you like to play again? (press 'y' or 'n')";
int promptLength = prompt.length(); // to check for added text
String input = null;
while (input == null || input.length() != 1 || "YyNn".indexOf(input) < 0)
{
    // if asking again, beep
    if (prompt.length() != promptLength)
    {
        java.awt.Toolkit.getDefaultToolkit().beep();
    }
    // ask question
    input = Greenfoot.ask(prompt);
    // if not already added, add extra text to prompt
    if (prompt.length() == promptLength)
    {
        prompt = "Invalid input -- please try again.\n\n"+prompt; // I believe the '\n' escape sequence is allowed here to create a new line
    }
}
if ("Nn".indexOf(input) < 0) // if not "No".
{
    Greenfoot.setWorld(new MyWorld()); // adjust class name as needed
}
else
{
    Greenfoot.stop();
}
You need to login to post a reply.