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

2016/4/11

generate a random 4-character secret

dhaval1704 dhaval1704

2016/4/11

#
hi i want to create a random 4 character secret but when i use getRandomNumber, it prints out the number instead of the character. I've added my code below. any help is appreciated thanks
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
public void generateSecret()
    {
        secret = "";
        int P = 0;
        int R = 1;
        int G = 2;
        int B = 3;
        secret ="" + getRandomNumber(0,3) + getRandomNumber(0,3) + getRandomNumber(0,3) + getRandomNumber(0,3) ;
        if(getRandomNumber(0, 3) == 0){
            P = 'P';
        }
        if(getRandomNumber(0, 3) == 1){
            R = 'R';
        }
         
        if(getRandomNumber(0, 3) == 2){
            G = 'G';
        }
         
        if(getRandomNumber(0, 3) == 3){
             B = 'B';
        }
         
        System.out.println("The secret is " + secret);
    }
danpost danpost

2016/4/11

#
Before beginning, I do not see a need to have the variables P, R, G and B; and the way you are changing them only creates a different number for their values (i.e. R = 'R'; results in the value of R to become something like 82). Then, I would presume you have a 'getRandomNumber' method in the class that is being called multiple times in your code (which should be shown). And then, the random values returned in line 8 have no consequence on what happens from line 9 through line 22 (calling the 'getRandomNumber' again would only return a new random number each time). Now, first thing I would do is change the way that you build the secret string by using a 'for' loop and calling a new method to return a random character:
1
for (int i=0; i<4; i++) secret += getRandomChar("PRGB");
The new method will return one of the four characters you included in your code:
1
2
3
4
private char getRandomChar(String characters)
{
    return characters.charAt(Greenfoot.getRandomNumber(characters.length));
}
Limiting the characters used in your secret drastically reduces the number of combinations for your secret. If one knew the four possible character used for the four character combination, they would only need to try 256 different combinations, at most.
danpost danpost

2016/4/11

#
Now if you wanted to create a four character secret using the entire alphabet, you could remove the parameter from the method and adjust the name of the method to call it with 'getRandomAlphaChar()' and then the method could be this:
1
2
3
4
private char getRandomAlphaChar()
{
    return (char)(65+Greenfoot.getRandomNumber(26));
}
The 26 is the number of characters in the alphabet and the 65 is the Unicode value pointing to the first one -- A.
You need to login to post a reply.