Random not working

Discussion in 'Plugin Development' started by XxZHALO13Xx, Jan 14, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    XxZHALO13Xx

    Why won't this random work?

    Code:
      public void randomMessage() {
            String[] messages = new String[]{ChatColor.DARK_GREEN + "test1", ChatColor.RED + "test2"};
            Random r = new Random();
            int numItems = r.nextInt(1) + 1;
            for (int i = 0; i < numItems; i++) {
                String string = null;
                string = messages[r.nextInt(messages.length)];
                String finalString = new String(string);
    
            }
    
        }
    p.sendMessage(randomMessage()); throws an error
     
  2. Offline

    SuperOriginal

    @XxZHALO13Xx
    • What's the point of the for loop if numItems is always 1 (the nextInt() method returns a value between 0 and the parameter you specified exclusively. aka you're getting a number between 0 and 0, then adding 1.)
    • Why are you constructing a new string when you can just use the "string" variable?
     
  3. You should learn the basics of Java before making Bukkit plugins. There's quite a bit wrong with even the basics of this... Anyway, the main problem is, your method is a void, not a String. You should return finalString. Also, why are you making a new string as SuperOriginal said above? No point.

    Since you probably won't know half the stuff I'm saying, I'll post the fixed code but please learn Java basics properly.

    Code:
       public String randomMessage() {
            String[] messages = new String[] { ChatColor.DARK_GREEN + "test1", ChatColor.RED + "test2" };
            Random r = new Random();
            return messages[r.nextInt(messages.length)];
        }
    
    Suggestion: You don't really need to make a new Random() instance every time, you could make it a private global variable.

    Edit: After seeing your signature, I'm extremely worried you're helping other people... You have two end brackets when only one is needed for that block of code.
     
    Last edited: Jan 14, 2015
    ResultStatic and SuperOriginal like this.
Thread Status:
Not open for further replies.

Share This Page