A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 付星 黑马帝   /  2012-1-1 17:07  /  2281 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 付星 于 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);

评分

参与人数 1技术分 +1 收起 理由
吴上储 + 1

查看全部评分

6 个回复

倒序浏览
  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);
复制代码

评分

参与人数 1技术分 +1 收起 理由
吴上储 + 1

查看全部评分

回复 使用道具 举报
你的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

评分

参与人数 1技术分 +1 收起 理由
王德云 + 1

查看全部评分

回复 使用道具 举报
word = new StringBuffer('P');
word = new StringBuffer('G');
word = new StringBuffer('M');
会调用StringBuffer(int capacity)的构造方法,即将字符转为int类型的变量,表示StringBuffer的大小,所以输出就会那样。
回复 使用道具 举报

这个应该是你的失误。你放的应该是字符串但是,你加的是字符,所以查找JDK API你会发现给本没有这个构造方法,但是有这样一个构造函数
StringBuffer(int capacity)
          构造一个不带字符,但具有指定初始容量的字符串缓冲区。
他会把你的字符转化成byte类型,这样只会限定你的缓冲区的大小。这是你的小小失误,自己注意点就行了,呵呵!

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
你把stringBuffer("")传送字符串,不要传入字符,还有就是swith这个要用break;喜欢程序会把执行那条语句后的所以语句执行一遍
回复 使用道具 举报
会把你的字符转化成byte类型,这样只会限定你的缓冲区的大小。这是你的小小失误
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马