没有构造函数接受 char 作为参数但有一个接受 int 作为容量.这就是您使用的那个... 您应该这样做: word = new StringBuilder();//不是StringBuffer//转变.然后:word.append("ain"); (还请注意,使用 StringBuilder 代替 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 ?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); }} 解决方案 Apart from the break problem, the main problem here is how you initialize your StringBuffer.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...You should do:word = new StringBuilder(); // not StringBuffer// switch. Then:word.append("ain");(also note the use of StringBuilder instead of StringBuffer; the latter is useful only in the rare case where thread-safety is required) 这篇关于& M'在哪里?去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 17:24
查看更多