2013-12-10 73 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). 
一個