我有这样的代码:
int q = 2;
int w = 3;
String str = "q = " + q + "\nw = " + w;
q++;
System.out.println(x+q);
是否可以刷新 str 中的 q,使输出不是 q = 2,而是 q = 3?
我的实际字符串要大得多,并且有更多参数。 它看起来很糟糕,因为我必须在 5 种不同的方法中使用该部分。
最佳答案
创建一个类来保存所有参数并根据需要生成一个字符串,例如:
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);
}
}
和
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();
关于java - 如何刷新字符串中的某些参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37243898/