[英]can't cast int to char with Java
I was given an assignment to generate a random number between 1 to 26 then convert that number to a letter from 'a' to 'z'. 给我分配了一个生成1到26之间的随机数,然后将该数字转换为从'a'到'z'的字母的任务。 the random generating part looks fine but when I try to cast the number to char, I would just get an empty square-like box!
随机生成部分看起来不错,但是当我尝试将数字转换为char时,我只会得到一个空的方形框! why is that?
这是为什么?
import java.util.Random;
public class NumbersToLetters
{
public static void main(String[] args)
{
Random n;
int num;
n=new Random();
//generating a random number from 1 to 26
num=Math.abs(((n.nextInt())%26)+1);
//cast from int to char
char myChar = (char) num;
System.out.println ("Number - " + num);
System.out.println ("Char - " + myChar);
//I'm sure that my answer is right but no matter what I do,
//it won't output a letter, all I get is a square-like box..
}
}
The character 'a'
is not encoded as 1
, but as 97
. 字符
'a'
未编码为1
,而是编码为97
。 You need to add 'a'
to a value between 0 and 25 (inclusive) to get the expected result: 您需要在0到25(含)之间的值上加上
'a'
以获得预期的结果:
num = 'a'+n.nextInt(26);
You're generating a number between 1 and 27 (inclusive). 您生成的数字介于1到27(含)之间。 If you look at what those characters correspond to , you'll see that none of them are actually printable.
如果查看这些字符对应的是什么 ,您会发现它们实际上都不是可打印的。
You should do your calculation as + 'a'
instead of + 1
您应该以
+ 'a'
而不是+ 1
来进行计算
n.nextInt(26) + 'a';
This will give you the correct offset (which happens to be 97) to find the lower case letters. 这将为您提供正确的偏移量(恰好是97)以查找小写字母。
I'm not a Java guru like others on here, but it might have something to do with not being encoded correctly? 我不是这里的Java专家,但可能与编码不正确有关吗? Look up UTF-8 encoding and just research type casting
查找UTF-8编码,然后研究类型转换
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.