【发布时间】:2013-12-17 12:23:32
【问题描述】:
我得到一个意外的输出来生成小写随机字母 - 我的代码是
public class CountLettersInArrayDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
CountLettersInArray ca = new CountLetterInArray();
char [] chars;
chars = ca.setCreateArray();
System.out.println(chars);
public class CountLettersInArray {
CountLettersInArray()
{}
//method to create an array
public char[] setCreateArray()
{
//declare an array
char [] chars = new char[100];
//initialize an array with random characters
for (int i=0;i<chars.length;i++)
{
chars[i]=(char)('a' + Math.random() * ('z' + 'a' -1));
}
return chars;
}
}
输出是 -
uěýyĬõĒēÕø»İäĂº±«Ċþÿd¢¼Ęÿuìăi±vÞ´Ĥč°ĩĒôĵ¶âþĂđďäÄĮÝă¤yÎĪÊíÆĭ××môÓâ¢ÓġÓ÷ÙĊïĺv×ĺît>
问:有什么想法是错误的吗?谢谢
【问题讨论】:
-
Math.random()内部最终使用Random.next(),所以不要使用Math.random(),因为不仅性能差很多,而且结果质量也不会像Random.next()或Random.nextDouble()stackoverflow.com/a/738651/995714 -
@luu - 我谨记您的建议。