-2

I am trying to write a method that replaces some Variables of a html code in a String to e.g. the source of an image etc.

String html = "<img src='IMAGE_SOURCE' width='IMAGE_WIDTH' align='IMAGE_ALIGN";

Now that's my String I've written three methods for:

public void setImageSource(String src) {
  html.replace("IMAGE_SOURCE", "Here comes the source for the image");
}

public void setImageWidth(String width) {
  html.replace("IMAGE_SOURCE", "Here comes the width for the image");
}

public void setImageAlign(String align) {
  html.replace("IMAGE_SOURCE", "Here comes the align for the image");
}

The methods get called, but the String "html" won't change. Any suggestions?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
user2410644
  • 3,861
  • 6
  • 39
  • 59

2 Answers2

3

You need to modify your code like:

html = html.replace("IMAGE_SOURCE", "Here comes the width for the image");

Strings in Java are constant, that means you can't change a string's value, you need a new string to store the result of your operation

Julian Suarez
  • 4,499
  • 4
  • 24
  • 40
0

Another potential problem I see:

You are using arguments called 'src', 'width', 'height', but you aren't using those variables in the functions. Do you mean to do something like:

String edited = src.replace("IMAGE_SOURCE", "Here comes the source for the image");
return edited;
Devon Parsons
  • 1,234
  • 14
  • 23