0

am using some simple code, which should get data from config

my config looks like:

name: test
locationA: -457.0,5.0,-186.0
locationB: -454.0,5.0,-186.0
prisonfile: ./plugins/JB/test.prison
prisons:
- -454.0,4.0,-176.0
- -460.0,4.0,-176.0
- -457.0,5.0,-186.0
police:
- -460.0,5.0,-186.0
- -454.0,5.0,-186.0
- -457.0,5.0,-176.0
open: true

my code looks like:

public void enter(Player player, String lines, String lines2) 
    {
        World world = player.getWorld();
        HashMap<String, Object> prison = plugin.prisons.getPrison(world.getName(), false);

        File configFile = new File(prison.get("config").toString());
        FileConfiguration config = YamlConfiguration.loadConfiguration(configFile);
        String listName = "police";
        List<String> list = config.getStringList(listName);
        Integer ListSize = list.size();
        Random r = new Random();
        int i1=r.nextInt(ListSize-1);
        String[] parts = list.get(i1).split(",");
        player.teleport(new Location(world, Float.parseFloat(parts[0]), Float.parseFloat(parts[1]), Float.parseFloat(parts[2])));

Code works corretly and teleporting me on random positions, but it always just port on first 2 positions and never port me on 3th one, i try to print out how many coordinations found ListSize in config and its 3 so i totaly dont understand.

p.s. i need to generate randoms between 0 and MaxNumber of positions

2 Answers 2

4

The problem is the argument to the nextInt method in this line:

int i1=r.nextInt(ListSize-1);

The range of the random number returned is 0 (inclusive) through n - 1, n being the parameter. Quoting from the Javadocs for the nextInt method:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

(emphasis mine)

There is no need to subtract 1 from the list size here. Try

int i1 = r.nextInt(ListSize);
Sign up to request clarification or add additional context in comments.

Comments

0

You need a good random and a good seed... so you could use one of

java.util.Random random = null; // Declare the random Instance.
random = new java.util.Random(
    System.currentTimeMillis());
// or
random = new java.util.Random(System.nanoTime());
// or
random = new java.util.Random(System.nanoTime()
    ^ System.currentTimeMillis());
// or
random = new java.security.SecureRandom(); // Because it makes "security" claims! :)

random.nextInt(MaxNumber + 1); // for the range 0-MaxNumber (inclusive).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.