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

2016/9/28

Variables in Greenfoot methods?

Gold_Leader Gold_Leader

2016/9/28

#
hi, I have some code here but I don't know why it isn't working. I thought it might be because I have the variable "target" for the Greenfoot meathod "isKeyDown" but there wasn't a syntax error. So i'm pretty clueless. help would be appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Penguin extends Actor
{
     
    public String input;
    private static final String letters = "abcdefghijklmnopqrstuvwxyz";
    public String target = "" + (char)letters.charAt(Greenfoot.getRandomNumber(26));
    public void act()
    {
        userLetter();
        getWorld().showText(input,356,62);
        getWorld().showText(target,306,62);
    }
    public void signLetter() {
        String target = "" + (char)letters.charAt(Greenfoot.getRandomNumber(26));       
    }
    public void userLetter() {
        if(Greenfoot.isKeyDown(target)) {
            signLetter();
        }
    }
}
danpost danpost

2016/9/29

#
The only problem I see is that the 'input' field is null. It never receives a String value. As null, any text already shown at the location will be cleared. Therefore, no error will ensue. Maybe you should assign the 'input' field the value of the 'target' field in the 'signLetter' method (before assigning a new value to 'target'. Oh, and remove the word 'String' from the beginning of line 14. With it, that assignment does not do anything to the field declared on line 6 and its value is lost when the method is exited.
Gold_Leader Gold_Leader

2016/9/30

#
Thanks a lot! You are a life saver!!! ^-^
You need to login to post a reply.