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

2013/4/1

How to select a random part of an array list

1
2
JetLennit JetLennit

2013/4/1

#
I would like to randomly select one of the parts of an array list and insert it where it says "this is where i want to insert the random splash"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import greenfoot.*;
import java.awt.Color;
 
public class splash  extends maintitle
{
    public void act()
    {
        updateImage();
    }
    private void updateImage()
    {
        setImage(new GreenfootImage("" + /*this is where i want to insert the random splash*/, 20, Color.GREEN, null));
    }
    public static String[] getSplashes()
    {
        String[] splashes = {"Shooting Aliens!", "Vwoorp!", "qul!", "Worf Does It!", "Make It So!", "Engage!",
        "It's A Trap!", "Trust Me, I'm The Doctor!"};
        return splashes;
    }
}
You either should insert code for random in that section, or have a random method. To use random, import java.util.Random, and make a new Random object in your random method:
1
2
3
4
public int random()
{
    Random r = new Random();
    ...
and tell it to return a random integer up to the length of the splashes:
1
return r.nextInt(getSplashes().length);
That should return a random splash.
JetLennit JetLennit

2013/4/1

#
what about the Greenfoot.getRandomNumber?
Oh, sorry, used to Random. Yes, you can use Greenfoot.getRandomNumber(getSplashes().length) That would be a lot easier.
Game/maniac Game/maniac

2013/4/1

#
I probably wrong but this might work: setImage(new GreenfootImage("" + getSplashes(), 20, Color.GREEN, null));
JetLennit JetLennit

2013/4/1

#
It just puts up a lot of random numbers...
JetLennit JetLennit

2013/4/1

#
Game/maniac's works!
Game/maniac wrote...
I probably wrong but this might work: setImage(new GreenfootImage("" + getSplashes(), 20, Color.GREEN, null));
Yah, i think that would work.
JetLennit JetLennit

2013/4/1

#
once i modify my code
Game/maniac Game/maniac

2013/4/1

#
setImage(new GreenfootImage("" + getSplashes(), 20, Color.GREEN, null)); might be better though if you add more splashes
JetLennit JetLennit

2013/4/1

#
Now i cant find out a way to avoid using the act method to update the image...
Game/maniac Game/maniac

2013/4/1

#
Update it in the constructor
JetLennit JetLennit

2013/4/1

#
what constructor?
Game/maniac Game/maniac

2013/4/1

#
This is a constructor if you didn't know:
1
2
3
4
public splash(/*variable go here*/)
{
    //code goes here
}
Game/maniac Game/maniac

2013/4/1

#
The constructor is called when you create the object
There are more replies on the next page.
1
2