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

xiaoxiao2021-02-28  92

昨天做笔试提的过程中遇到一个问题: 如何把 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

转载请注明原文地址: https://www.6miu.com/read-67104.html

最新回复(0)