views:

62

answers:

4

Hi,

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') ;
    }
}
A: 

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
pyCoder
+3  A: 

Your code is printing characters that cannot be displayed by the console or its font.

SLaks
Hi SLaks, i tried to write it to a file but it also wrote a '?'
Baba
@Baba: You need to write it to a Unicode file.
SLaks
What did you specify as file encoding? Use UTF-8.
Neeme Praks
ok thanks! can this be done by amending this linejava.io.File file = new java.io.File("myFile.txt");i'll look it up anyway. thanks for your help!
Baba
A: 

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.

A: 

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;};
     }
    }
Michael Konietzka