问题描述
我在String Buffer中玩了一下,并注意到混合字符和字符串是一个坏主意。我希望我的下面的代码可以打印Main,但是只是得到了一个ain。
I played a bit around with String Buffer and noticed, that mixing chars and String is a bad idea. I expected my following code to print "Main", however just got an "ain".
显然,word是使用String Buffer构造函数的char版本初始化的,但是我测试了几个方法,比如toString或getIndex(),但在ain旁边找不到任何东西。 - 这让我想知道:构造函数做了什么?它有用吗?可以通过单词再次检索M吗?
Clearly word was initialized with the char version of the String Buffer constructor, however I tested several methods like toString or getIndex( ), but could not find anything beside "ain" - which makes me wonder: What did the constructor do? Is there a usage for it? Can the 'M' somehow be retrieved again from word ?
import java.util.Random;
public class OrNotPublicClass {
private static Random rnd = new Random();
public static void main(String[] args) {
StringBuffer word = null;
switch (rnd.nextInt(2)) {
case 1:
word = new StringBuffer('P');
case 2:
word = new StringBuffer('G');
default:
word = new StringBuffer('M');
}
word.append("ain");
System.out.println(word);
}
}
推荐答案
分开从中断
问题,这里的主要问题是如何初始化 StringBuffer
。
Apart from the break
problem, the main problem here is how you initialize your StringBuffer
.
没有构造函数接受 char
作为参数, 。
There is no constructor accepting a char
as an argument, but there is one accepting an int
for the capacity.
这就是你使用的那个......
And that is the one you use...
你应该这样做:
word = new StringBuilder(); // not StringBuffer
// switch. Then:
word.append("ain");
(另请注意使用 StringBuilder
代替 StringBuffer
;后者仅在需要线程安全的极少数情况下有用)
(also note the use of StringBuilder
instead of StringBuffer
; the latter is useful only in the rare case where thread-safety is required)
这篇关于'M'去哪儿了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!