为什么Java中int强转char可打印ASCII,使用变量时却不行?
问题原因分析
你第一段代码可以正常打印A的原因很简单:将65.25强制转为char类型时,会自动截断小数部分得到整数值65,而ASCII编码规则中十进制值65刚好对应可打印的大写字母A,因此输出符合预期。
你第二段代码无法打印可见ASCII字符的核心原因是:
- 你通过
(int)currentSeconds % 26计算得到的rand取值范围是0~25 - ASCII编码中031区间的字符全部是不可见的控制字符(比如空字符、换行符、转义字符等),32才是第一个可见字符(空格),65才对应大写字母A,因此你直接把025的数值转为char打印,自然看不到正常的可打印字符。
修复方案
如果你的目标是随机生成大写字母,只需要在转char的时候加上偏移量65(或者直接用字符'A',可读性更好)即可:
// 把原来的char randN = (char)rand; 替换为下面的代码 char randN = (char)('A' + rand);
修复后的完整运行逻辑如下:
System.out.println(System.currentTimeMillis()); System.out.println(" using current second to generate random Uppercase letter"); long totalsecs = System.currentTimeMillis()/1000; long currentSeconds = totalsecs % 60; long totalMinute = totalsecs/60; long currentMinute = totalMinute%60; long totalHours = totalMinute/60; long currentHours = totalHours%24; System.out.println("current time is " +currentHours +":"+ currentMinute +":"+currentSeconds); int rand = (int)currentSeconds % 26; System.out.println(" the number is " + rand); // 修正后代码,加上'A'的偏移量 char randN = (char)('A' + rand); System.out.println(randN);
这样rand为0时对应A,rand为25时对应Z,刚好覆盖所有大写英文字母。
内容的提问来源于stack exchange,提问作者Mani
相关产品推荐
相关产品推荐

