- /*
- import java.util.Random;
- public class Rhymes
- {
- private static Random rnd = new Random();
- public static void main(String[]args)
- {
- StringBuffer word = null;
- switch(rnd.nextInt(2))//此处应是3,生成的随机数是0和指定值之间的数,不包括指定值
- {
- case 1: word = new StringBuffer('P'); //此处应传入字符串而不是字符,而且缺少break;否则只赋值最后一个
- case 2: word = new StringBuffer('G'); //至于为什么传入错误的数据类型可以成功创建对象,不太清楚
- default: word = new StringBuffer('M');
- }
- word.append('a');
- word.append('i');
- word.append('n');
- System.out.println(word);
- }
- }
- */
- //下面对原代码做了一下改善,结果是成功的
- import java.util.Random;
- public class Demo
- {
- private static Random rnd = new Random();
- public static void main(String[]args)
- {
- for (int i=1;i<20;i++ )
- {
- StringBuffer word = null;
- switch(rnd.nextInt(3))
- {
- case 0: word = new StringBuffer("P"); break;
- case 1: word = new StringBuffer("G"); break;
- default: word = new StringBuffer("M");
- }
- word.append('a');
- word.append('i');
- word.append('n');
- System.out.println(word);
- }
- }
- }
复制代码 |