为什么我在Java中使用char和int进行比较? [英] Why doesn't my compare work between char and int in Java?

查看:405
本文介绍了为什么我在Java中使用char和int进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char c = '0';
int i = 0;
System.out.println(c == i);

为什么这总是返回false?

Why does this always returns false?

推荐答案

虽然这个问题很不清楚,但我很确定海报想知道为什么打印 false

Although this question is very unclear, I am pretty sure the poster wants to know why this prints false:

char c = '0';
int i = 0;
System.out.println(c == i);

答案是因为每个可打印字符都分配了一个唯一的代码编号,这就是一个 char 在被视为 int 时。字符 0 的代码编号为十进制48,显然48不等于0.

The answer is because every printable character is assigned a unique code number, and that's the value that a char has when treated as an int. The code number for the character 0 is decimal 48, and obviously 48 is not equal to 0.

为什么不是数字的字符代码是否等于数字本身?主要是因为前几个代码,特别是 0 ,太过特殊,无法用于这种平凡的目的。

Why aren't the character codes for the digits equal to the digits themselves? Mostly because the first few codes, especially 0, are too special to be used for such a mundane purpose.

这篇关于为什么我在Java中使用char和int进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆