Silvasky Silvasky - 6 months ago 19
Java Question

How can I refresh some parameters in a String?

I have a code like:

int q = 2;
int w = 3;
String str = "q = " + q + "\nw = " + w;

q++;
System.out.println(x+q);


Is it possible to refresh the q in str, so the Output is not q = 2, rather q = 3?

My actual String is a lot bigger, and has more Parameters.
It looks terrible, cause I have to use that piece in 5 different Methods.

Answer

Create a class that holds all parameters and generates a string for demand, something like:

class MyStringGenerator{
  private int q;
  private int w;
  setQ(int q ){
    this.q = q;
  }
  setW( int w ){
    this.w = w;
  }

  public String getMyString(){
    return String.format("q = %d \nw = %d", q, w);
  }
}

and

MyStringGenerator msg = new MyStringGenerator();
int q = 2;
int w = 3;
msg.setQ( q );
msg.setW( w );

String str = msg.getMyString();

q++;
System.out.println(x+q);
msq.setQ( q ); // set a new value of Q
String newString = msg.getMyString();