2013-12-10 31 views
0

随机数正在使用一些简单的代码,它应该从配置数据生成Java

我的配置是这样的:

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 

我的代码如下所示:

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]))); 

代码工作将它们传送给我随机的位置,但它总是在前两个位置移动,并且不会在第三个位置移动我,我尝试打印出在配置中发现了多少个协调列表并且发现了3个ListSize,因此我总是不明白。

p.s.我需要0位置

回答

4

问题的MAXNUMBER和之间产生随机量是参数到nextInt方法在这一行:

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

返回的随机数的范围是0(含)通过n - 1n是参数。从the Javadocs for the nextInt method引述:

返回一个伪随机均匀分布的int值介于0(含)和指定值(不含),从该随机数生成器的序列绘制。

(重点煤矿)

没有必要从这里列表大小减去1。尝试

int i1 = r.nextInt(ListSize); 
0

你需要一个良好的随机和良好的种子...所以你可以使用的

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). 
一个