我得到一个意外的输出来生成小写随机字母 - 我的代码是
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×李÷dĤĸt
答案 0 :(得分:1)
试试这个
chars[i]=(char)('a' + Math.random() * ('z' - 'a'));
或只是
chars[i]=(char)('a' + Math.random() * 26);
答案 1 :(得分:1)
您的代码存在小问题,
您正在使用chars[i]=(char)('a' + Math.random() * ('z' + 'a' -1));
相反,试试这个,
for (int i=0;i<chars.length;i++)
{
chars[i]=(char)('a' + Math.random() * ('z' - 'a') );
}
或者更快一点,
char Diff = 'z' - 'a';
for (int i=0;i<chars.length;i++)
{
chars[i]=(char)('a' + Math.random() * Diff);
}
只是说明您正尝试使用简单的公式在范围之间生成整数,
Min + (int)(Math.random() * ((Max - Min) + 1))
但是在您的代码中,您犯了一个小错误Max + Min
而不是Max - Min
答案 2 :(得分:0)
您可以尝试以下内容:
Random random = new Random();
for(int i = 0; i<chars.length;i++){
chars[i] = (char)(random.nextInt('z'-'a') + 'a');
}
答案 3 :(得分:0)
尝试this.it会随机生成8个字符的字符串
public String randomString() {
int len = 8;
String alphaNumericString = "abcdefghijklmnopqrstuvwxyz1234567890";
// creating the object for string builder
StringBuilder sb = new StringBuilder(len);
try {
String PASSSTRING = alphaNumericString;
// creating the object of Random class
Random rnd = new Random();
for (int i = 0; i < len; i++) {
// generating random string
sb.append(PASSSTRING.charAt(rnd.nextInt(PASSSTRING.length())));
}
} catch (Exception e) {
e.printStackTrace();
}
// returning the random string
return sb.toString();
}// randomString()
答案 4 :(得分:0)
不要重新发明轮子。使用commons-lang3
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
...
randomAlphabetic(length).toLowerCase()
答案 5 :(得分:0)
这个选项怎么样: ( a+ Math.random() * b) - 返回 a 和 a+b 之间的随机数,不包括 a+b 'a'to'z' 十进制值:97 到 122;
Random rand = new Random();
char a = (char) (97+(int)(Math.random()*25));
System.out.println(a);