无法使用Java将int转换为char [英] can't cast int to char with Java
问题描述
我被分配了一个生成介于1到26之间的随机数,然后将该数字转换为从 a到 z的字母的任务。
随机生成的部分看起来不错,但是当我尝试将数字强制转换为char时,我只会得到一个空的方形框!
为什么?
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'. 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! 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..
}
}
推荐答案
您生成的数字介于1到27(含)之间。如果您查看这些字符所对应的,您会发现它们实际上都不是可打印的。
You're generating a number between 1 and 27 (inclusive). If you look at what those characters correspond to, you'll see that none of them are actually printable.
您应使用 +'a'
而不是 +1
n.nextInt(26) + 'a';
这将为您提供正确的偏移量(恰好是97)以查找小写字母。
This will give you the correct offset (which happens to be 97) to find the lower case letters.
这篇关于无法使用Java将int转换为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!