plitting strings

Discussion in 'Plugin Development' started by arjanforgames, Nov 27, 2013.

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

    arjanforgames

    I have a sword with the lore: "Damage: 5" at the first line.
    Now how van I split the string to see if it says "damage" and then pass the number behind the : to an int
    So I can use it to modify the damage etc. (Do know how to do that)
     
  2. Offline

    felixfritz

    You could do word.split(": ");. Therefore, in index 0 is "Damage" and in index 1 is "5".
     
  3. Offline

    M0n0clink

    You can do it like this
    Code:java
    1. String[] splitted = line.split(":")
    2.  
    3. if(splitted[0] == "Damage"){
    4.  
    5. int dam = Integer.parseInt(splitted[1]);
    6. // Modify damage
    7.  
    8. }
     
  4. Offline

    arjanforgames

    I've got it set up like this:
    Code:java
    1. List<String> lore = player.getItemInHand().getItemMeta().getLore();
    2. String line = lore.toString();
    3. ChatColor.stripColor(line);
    4. String[] splitted = line.split(":");
    5. if(splitted[0] == "Damage"){
    6. System.out.println("test");
    7. int dam = Integer.parseInt(splitted[1]);
    8. Bukkit.broadcastMessage(dam + " DAMAGE!");
    9. }


    It doesnt give me any errors but I had some debug message's and it seems the script is not getting past the: " if(splitted[0] == "Damage"){"

    This is my sword:
    [​IMG]
     
  5. Offline

    felixfritz

    Compare strings using the equals or equalsIgnoreCase-method
    Code:java
    1. if(splitted[0].equals("Damage");

    Also, be aware that the second part of the array which contains the number, must not contain any other characters other than 0 through 9. Right now, there will be a whitespace in there, which is going to throw a NumberFormatException.

    To prevent this, you can either split the whitespace after the semicolon with it(like I suggested at first: line.split(": "); ), or you replace all the whitespace inside the string.
    Code:java
    1. int dam = Integer.parseInt(splitted[1].replace(" ",""));
     
  6. Offline

    arjanforgames

    It just doesn't seem to work.
    I doesn't throw an error but just nothing is happening.
     
Thread Status:
Not open for further replies.

Share This Page