user425727
user425727

Reputation:

print char using unicode value (java)

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

Answers (4)

Michael Konietzka
Michael Konietzka

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

user492883
user492883

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

SLaks
SLaks

Reputation: 888203

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

Upvotes: 2

pyCoder
pyCoder

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

Related Questions