我想在运行时对字符串进行一些更改。在下面的代码中我试图改变int变量count
,以便字符串s也会改变。
我认为的结果是这样的:
You have invited 0 users.
You have invited 5 users.
但在这两种情况下都有0:
You have invited 0 users.
You have invited 0 users.
能否请您解释一下为什么我的想法不起作用,我应该做些什么让它起作用?
static int count;
static String s = "You have invited " + count + " users.";
public static void main(String[] args) {
System.out.println(s);
count = 5;
System.out.println(s);
}
您可以创建一个访问器方法,如getter
,并使您的count
成为一个实例变量:
private int count = 0;
private String getString(){
return "You have invited " + this.count + " users.";
}
然后可以像这样调用:
System.out.println(getString()); // prints: You have invited 0 users.
this.count = 5;
System.out.println(getString()); // prints: You have invited 5 users.
这是因为就像在@YCF_Ls中已经说过的那样,回答Strings
是不可变的。这意味着一旦创建了字符串。它无法改变。唯一的方法是使用新的String覆盖它(它仍然不会更改值,但只会将变量s
的引用更改为新字符串)
字符串是不可变的,所以当你使用count = 5;
时实际上你并没有改变s
。要进行更改,您必须使用:
count = 5;
s = "You have invited " + count + " users.";
System.out.println(s);
字符串是不可变的。每次,您对现有字符串进行任何更改,都需要重新分配,以反映更改。在您的情况下,您已更改计数变量。但是,在更改它之后,您需要将字符串重新分配给变量s
。或者,简单来说,您需要使用count
变量创建新字符串并将其分配给某个变量,即在您的情况下,它是s
正如其他人所说,你对count
的修改不会改变s
的价值。
你可以做的是使用String.format(String , Object...):
static final String s = "You have invited %d users.";
// then later...
System.out.println(String.format(s, count));
虽然计数已经改变,但是s没有改变,并且一直是“你邀请了0个用户”。
1.int count是基本数据类型变量。
2.即使count是引用类型,String也是不可变的,除非重新赋值。
static int count;
static String s = "You have invited " + count + " users.";
public static void main(String[] args) {
System.out.println(s);
count = 5;
s = "You have invited " + count + " users.";
System.out.println(s);
}
static int count;
public static void main(String[] args) {
printCount();
count = 5;
printCount();
}
public static void printCount() {
System.out.println("You have invited " + count + " users.");
}