Reputation: 95
i am getting an unexpected output to generate lower case random letters - my code is
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;
}
}
output is -
uěýyĬõĒēÕø»İäĂº±«Ċþÿd¢¼Ęÿuìăi±vÞ´Ĥč°ĩĒôĵ¶âþĂđďäÄĮÝă¤yÎĪÊíÆĭ××môÓâ¢ÓġÓÙĊïĺv×ĺî÷dĤĸt
Q: any ideas where the mistake is ? thanks
Upvotes: 1
Views: 8491
Reputation: 121
How about this option: ( a+ Math.random() * b) - return a random number between a and a+b, excluding a+b 'a'to'z' Decimal value: 97 to 122;
Random rand = new Random();
char a = (char) (97+(int)(Math.random()*25));
System.out.println(a);
Upvotes: 0
Reputation: 14550
don't reinvent the wheel. use commons-lang3
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
...
randomAlphabetic(length).toLowerCase()
Upvotes: 0
Reputation: 6276
There is small problem associated with your code,
You are using chars[i]=(char)('a' + Math.random() * ('z' + 'a' -1));
Instead try this,
for (int i=0;i<chars.length;i++)
{
chars[i]=(char)('a' + Math.random() * ('z' - 'a') );
}
or a little faster way,
char Diff = 'z' - 'a';
for (int i=0;i<chars.length;i++)
{
chars[i]=(char)('a' + Math.random() * Diff);
}
Just EXPLANATION You are trying to generate integers between a range using the simple formula,
Min + (int)(Math.random() * ((Max - Min) + 1))
But in your code you have made a small mistake Max + Min
instead of Max - Min
Upvotes: 1
Reputation: 5376
try this.it will generate 8 characters random String
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()
Upvotes: 0
Reputation: 136062
try this
chars[i]=(char)('a' + Math.random() * ('z' - 'a'));
or simply
chars[i]=(char)('a' + Math.random() * 26);
Upvotes: 1
Reputation: 3658
What you could try is the following:
Random random = new Random();
for(int i = 0; i<chars.length;i++){
chars[i] = (char)(random.nextInt('z'-'a') + 'a');
}
Upvotes: 0