简体   繁体   English

使用unicode值打印char(java)

[英]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') ;
    }
}

您的代码正在打印控制台或其字体无法显示的字符。

Use Random class instead of Math.random(). 使用随机类代替Math.random()。 (But in prompt command if you don't ave extension map installed you cannot see unicode character but only ascii) (但是如果您没有安装扩展映射,则在提示命令中,您无法看到unicode字符,但只能看到ascii)

You cane get integer number using .nextInt() method of Random object. 您可以使用Random对象的.nextInt()方法获取整数。

Example: 例:

if you want a random number from 1 to 40 you can write: 如果您想要一个从1到40的随机数,可以这样写:

Random numRandom = new Random();
int n = numRandom.nextInt(40) + 1; // nextInt(40) give a number from 0 to 39

you can convert them into ascii: 你可以将它们转换为ascii:

(char) ((int)(Math.abs(ch1 + Math.random() * ( ch2 - ch1 )) % 128)) (字符)((int)(Math.abs(ch1 + Math.random()*(ch2-ch1))%128))

that should display only ascii chars from 0-127 on your console. 应该在控制台上仅显示0-127之间的ascii字符。

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. 您的实现有时会返回未定义的字符,因为并非char的每个值都是有效的unicode字符。 Character.isDefined(char ch) offers a check if a char is defined in Unicode. Character.isDefined(char ch)检查是否在Unicode中定义了char。 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. 一个快速的解决方案可能看起来像这样,但是当对随机过程使用错误的边界(仅包含无效的char值)时,当然可以无限运行。

public static char getRandomCharacter(char ch1, char ch2)
    {
     while (true)
     {
      char ch=(char)(ch1 + Math.random() * ( ch2 - ch1 )) ;
      if (Character.isDefined(ch)) {return ch;};
     }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM