StringBuffer 的一个骗子

package stringProblem;

import java.util.Random;

/*
 * p 49
 */
public class Rhymes {
    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('a');
	word.append('i');
	word.append('n');
	System.out.println(word);
	test();
	test2();
   }
    // 这是满足上面要求一个更加优雅的代码 
    public static void test() {
	System.out.println("PGM".charAt(rnd.nextInt(3))+"ain");
    }
    // 来个更加经典的
    public static  void test2() {
	String a[] = {"Main","Pain","Gain"};
	System.out.println(randomElement(a));
    }
    private static String randomElement(String[]a) {
	return a[rnd.nextInt(a.length)];
    }
}
/*
 *	对于上面的程序有三处错误
 *	1.random.nextInt(2) 只会返回  0 ,1,所以永远达不到 2
 *	2.switch case 中没有 break;最后会返回最后一个case
 *	3.对于 StringBuffer 中并没有 new StringBuffer(char)的构造,只有
 *	StringBuffer(String) StringBuffer(int),所以会将 char 转成其相应的
 *	int 值 ,所以上面会输出 ain  	
 * */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值