Reputation:
Below code returns ?
rather than a random character. Any ideas? Please note that i wrote this as pat of an exercise on method overloading hence the 'complicated' setup.
class TestRandomCharacter
{
public static void main(String[] args)
{
char ch = RandomCharacter.getRandomCharacter() ;
System.out.println(ch);
}//end main
}
class RandomCharacter
{
public static char getRandomCharacter(char ch1, char ch2)
{
return (char)(ch1 + Math.random() * ( ch2 - ch1 )) ;
}
public static char getRandomCharacter()
{
return getRandomCharacter('\u0000','\uFFFF') ;
}
}
Upvotes: 0
Views: 1690
Reputation: 5499
As already mentioned you have a problem with your console, enconding and fonts.
Nevertheless:
Your implementation will return undefined characters sometimes, because not every value of char is a valid unicode character. Character.isDefined(char ch) offers a check if a char is defined in Unicode. A quick solution could look like this, but can of course run endless when using bad boundaries for the random process, containing only invalid char-values.
public static char getRandomCharacter(char ch1, char ch2)
{
while (true)
{
char ch=(char)(ch1 + Math.random() * ( ch2 - ch1 )) ;
if (Character.isDefined(ch)) {return ch;};
}
}
Upvotes: 0
Reputation: 101
you can convert them into ascii:
(char) ((int)(Math.abs(ch1 + Math.random() * ( ch2 - ch1 )) % 128))
that should display only ascii chars from 0-127 on your console.
Upvotes: 0
Reputation: 888203
Your code is printing characters that cannot be displayed by the console or its font.
Upvotes: 2
Reputation: 501
Use Random class instead of Math.random(). (But in prompt command if you don't ave extension map installed you cannot see unicode character but only ascii)
You cane get integer number using .nextInt() method of Random object.
Example:
if you want a random number from 1 to 40 you can write:
Random numRandom = new Random();
int n = numRandom.nextInt(40) + 1; // nextInt(40) give a number from 0 to 39
Upvotes: 0