java如何将char类型的数字转换成int型的数字

来源:互联网 发布:软件项目管理实例 编辑:程序博客网 时间:2024/05/22 15:48

昨天做笔试提的过程中遇到一个问题: 如何把 char ‘3’ 转为 int 3, 大家应该知道,不能直接转化,那样得到是‘3’的Ascii. 如下面:

public class CharToIntConverter {        public static void main(String[] args) {            char numChar = '3';            int  intNum = numChar;            System.out.println(numChar + ": " + intNum);        }    }
输出结果如下:

3: 51

那如果要把char '3'转为int 3该怎么做呢,查了一点资料,发现了一个最简单的方法:

public class CharToIntConverter {        public static void main(String[] args) {            char numChar = '3';            int  intNum = numChar - '0';            System.out.println(numChar + ": " + intNum);        }    }
直接在numChar后面减去'0'即可,输出结果如下:

3: 3


阅读全文
0 0