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
* */
StringBuffer 的一个骗子
最新推荐文章于 2024-03-19 09:30:00 发布