黑马程序员技术交流社区

标题: 为什么程序只是打印着ain [打印本页]

作者: 付星    时间: 2012-1-1 17:07
标题: 为什么程序只是打印着ain
本帖最后由 付星 于 2012-1-3 17:14 编辑

                                Random rnd = new Random();
                StringBuffer word = null;
                switch(rnd.nextInt(3)) {
                case 1: word = new StringBuffer('P');
                case 2: word = new StringBuffer('G');
                default: word = new StringBuffer('M');
                }
                word.append('a');
                word.append('i');
                word.append('n');
                System.out.println(word);
作者: 杨旭    时间: 2012-1-1 19:48
  1.         Random rnd = new Random();
  2.         StringBuffer word = null;
  3.         switch(rnd.nextInt(3)) {
  4.         case 0: word = new StringBuffer("P");break;
  5.         case 1: word = new StringBuffer("G");break;
  6.         default: word = new StringBuffer("M");break;
  7.         }
  8.         word.append('a');
  9.         word.append('i');
  10.         word.append('n');
  11.         System.out.println(word);
复制代码

作者: 李盈科    时间: 2012-1-1 19:50
你的word = new StringBuffer('P'); 初始化错了!应该写成word = new StringBuffer(“P”); 要双引号!
StringBuffer 的构造方法一共四种

第一个是 public StringBuffer():Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
第二种是public StringBuffer(int capacity):Constructs a string buffer with no characters in it and the specified initial capacity.
第三种是 public StringBuffer(String str):Constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is  16          plus the length of the string argument.
第四种是 public StringBuffer(CharSequence seq):Constructs a string buffer that contains the same characters as the specified CharSequence. The initial  capacity of the string buffer is 16 plus the length of the CharSequence argument.
If the length of the specified CharSequence is less than or equal to zero, then an empty buffer of capacity 16 is returned.

CharSequence seq 是一个接口  实现类为CharBuffer, Segment, String, StringBuffer, StringBuilder


作者: 颜宗茂    时间: 2012-1-1 20:30
word = new StringBuffer('P');
word = new StringBuffer('G');
word = new StringBuffer('M');
会调用StringBuffer(int capacity)的构造方法,即将字符转为int类型的变量,表示StringBuffer的大小,所以输出就会那样。
作者: 想好了再写    时间: 2012-1-2 18:57

这个应该是你的失误。你放的应该是字符串但是,你加的是字符,所以查找JDK API你会发现给本没有这个构造方法,但是有这样一个构造函数
StringBuffer(int capacity)
          构造一个不带字符,但具有指定初始容量的字符串缓冲区。
他会把你的字符转化成byte类型,这样只会限定你的缓冲区的大小。这是你的小小失误,自己注意点就行了,呵呵!
作者: 沈样    时间: 2012-1-2 19:09
你把stringBuffer("")传送字符串,不要传入字符,还有就是swith这个要用break;喜欢程序会把执行那条语句后的所以语句执行一遍
作者: lvwenwen88    时间: 2012-1-4 21:00
会把你的字符转化成byte类型,这样只会限定你的缓冲区的大小。这是你的小小失误




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2