& M'在哪里?去? [英] Where did the 'M' go?
问题描述
我对String Buffer玩了一点,发现混合使用char和String是一个坏主意.我希望我的以下代码可以打印"Main",但是只有一个"ain".
很明显,单词是用String Buffer构造函数的char版本初始化的,但是我测试了诸如toString或getIndex()的几种方法,但是找不到"ain"旁边的任何东西-这让我感到奇怪:构造函数做了什么?有用途吗?可以通过某种方式再次从单词中检索"M"吗?
import java.util.Random;公共类OrNotPublicClass {私有静态随机数rnd =新的Random();公共静态void main(String [] args){StringBuffer word = null;开关(rnd.nextInt(2)){情况1:字=新的StringBuffer('P');情况2:字=新的StringBuffer('G');默认:字=新的StringBuffer('M');}word.append("ain");System.out.println(word);}}
除了 break
问题之外,这里的主要问题是如何初始化 StringBuffer
.>
没有构造函数接受 (还请注意,使用 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". 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 ?
Apart from the There is no constructor accepting a And that is the one you use... You should do: (also note the use of 这篇关于& M'在哪里?去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! char
作为参数 StringBuilder
代替 StringBuffer
;后者仅在极少数需要线程安全的情况下有用)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);
}
}
break
problem, the main problem here is how you initialize your StringBuffer
.char
as an argument, but there is one accepting an int
for the capacity.word = new StringBuilder(); // not StringBuffer
// switch. Then:
word.append("ain");
StringBuilder
instead of StringBuffer
; the latter is useful only in the rare case where thread-safety is required)