-2

I have been working on some Java code and I came across a really weird error, Im trying to replace a piece of string with an Integer. Added all kinds of debugs but I cant seem to find it out.

private void executeMsg() {
    value = value.replaceAll("(&([a-f0-9]))", "§$2");

    String border = tostiuhc.getWorldManager().getBorderSize() - tostiuhc.getShrinksize() + "";
    String time = tostiuhc.getPhase().getMinutes() + "";

    System.out.println("BORDER: " + border);
    System.out.println("TIME: " + time);

    value = value.replace("-border-", border + "");
    value = value.replace("-time-", time + "");

    tostiuhc.broadcast(value + " " + time);
}

As you can see, I create new String called 'time' and print it out 'TIME: value'. The original string that I'm changing is: The event is now -time- minutes in!

enter image description here

enter image description here

The problem here is that System.out.println("TIME:") shows the correct value, but the .replace just DOESNT work. I cant get my head around this, anyone has any idea?

Bram
  • 97
  • 8
  • 3
    The quoted output is useless, as it doesn't ever include outputting `value` after the `replace`. What do you see when you debug this? What *is* `value`? Looks like an instance field, meaning that `-time-` won't be present the second time you do this. This really just calls for basic debugging. – T.J. Crowder Jun 07 '15 at 21:18
  • Where exactly are you trying to replace a string with an int? – Andreas DM Jun 07 '15 at 21:19
  • @AndreasDM Right here: value = value.replace("-time-", time + ""); I changed it to a String already. – Bram Jun 07 '15 at 21:21
  • 1
    And what is the initial value of `value`? – Tom Jun 07 '15 at 21:22
  • @T.J.Crowder the tostiuhc.broadcast(value + " " + time); is "The event is now 0 minutes in! 0" – Bram Jun 07 '15 at 21:22
  • @Tom "The event is now -time- minutes in!" – Bram Jun 07 '15 at 21:23
  • @Harm-Jan: Can you add a `System.out.println(value);` just before the replace? What does it print? – sstan Jun 07 '15 at 21:26

1 Answers1

5

The replace only works on the first execution. After that, value no longer contains -time-. As a solution, you can use a temporary variable to do your replacement:

String displayValue = value.replace("-time-", time + "");
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • oh, so `value` is a global variable? I think you might be right! Curious to see if OP confirms. – sstan Jun 07 '15 at 21:25
  • @sstan How could it not be? Besides, look at the screenshot in the original post. – shmosel Jun 07 '15 at 21:27
  • And to make it even better, he should pass the String to the methos as an argument :D. – Tom Jun 07 '15 at 21:32
  • You sir, deserve a big cookie, I have been hitting my head for so long on this. It's so funny to see now, thank you so much for the help! I will accept this answer asap. – Bram Jun 07 '15 at 21:34
  • @shmosel oh so intelligent solution..it saved my time! Thank you. – limonik Dec 28 '15 at 00:19