如何把char类型的数字字符转换成int类型

£神魔★判官ぃ 2022-05-26 07:35 326阅读 0赞

近来面试遇到一个问题,通过控制台输入一个12位的数字,然后进行一些计算,然后被困在如何把char类型的数字转换成int类型。通过搜索,找到两个解决办法。

1、把char型转换成int类型

  1. for(int i = 0;i<str.length();i++)
  2. {
  3. char temp_char = str.charAt(i);
  4. //把字符转换成数字方法一
  5. int temp_int = temp_char-'0';
  6. //把字符转换成数字方法二
  7. int temp_int = Integer.parseInt(String.valueOf(temp_char));
  8. }

第一种办法:通过charAt(i),把字符串的每位变成char型,然后用当前字符减去字符0 (temp_char-‘0’),得到当前字符的int值。

第二种办法:把字符再转成字符串,然后再强制转换成int型。

2、把字符串拆分成一位一位的

第一种方法:循环后charAt(i);

注意:charAt(i)得到的是字符串对应的每位字符,可是不能直接转成int,转成int依然是ASCII值。

第二种方法:char[] temp = str.toCharArray();

注意:char[]里的内容不是字符串的每位字符,而是每位字符的ASCII值。

具体面试题如下:

  1. package cjl;
  2. import java.util.Scanner;
  3. /**
  4. * 一维码有一种编码是ean13,是一串13位数字。其中第13位是校验码,作用是校验前面12个数字是否正确。
  5. * 校验方法如下:
  6. * 1、前12位数字从左起,将所有的奇数位相加得出一个数a,将所有的偶数位相加得出一个数b
  7. * 2、将数b乘以3再与a相加得到数c
  8. * 3、用10减去数c的个位数,如果结果不为10则校验码为结果本身,如果为10则校验码为0
  9. * 请在控制台任意输入一个12位数字,然后输出校验码
  10. * @author ff
  11. *
  12. */
  13. public class CheckCode {
  14. public void checkCode(String str)
  15. {
  16. int checkCode = 0;
  17. int a = 0;//奇数位的和
  18. int b = 0;//偶数位的和
  19. for(int i = 0;i<str.length();i++)
  20. {
  21. char temp_char = str.charAt(i);
  22. //把字符转换成数字方法一
  23. int temp_int = temp_char-'0';
  24. //把字符转换成数字方法二
  25. //int temp_int = Integer.parseInt(String.valueOf(temp_char));
  26. //System.out.println("temp_char = "+temp_char);
  27. //System.out.println("temp__int = "+temp_int);
  28. if((i+1)%2==0)//偶数位
  29. {
  30. b+=(int)temp_int;
  31. }
  32. else //奇数位
  33. {
  34. a = a+(int)temp_int;
  35. }
  36. }
  37. int c = a+b*3;
  38. int c_gw = c%10;
  39. int d = 10-c_gw;
  40. //System.out.println("a = "+a+" b = "+b+" c = "+c+" c_gw = "+c_gw+" d = "+d);
  41. if(d==10)
  42. {
  43. checkCode= 0;
  44. }
  45. else
  46. {
  47. checkCode= d;
  48. }
  49. System.out.println("checkCode = "+checkCode);
  50. }
  51. public void Input()
  52. {
  53. while (true) {
  54. Scanner scanner = new Scanner(System.in);
  55. System.out.println("请输入一个12位的数字。。。。。。");
  56. String str = scanner.nextLine();
  57. if((str.length()==12)&&(str.matches("[0-9]+")))
  58. {
  59. checkCode(str);
  60. break;
  61. }
  62. }
  63. }
  64. /**
  65. * @param args
  66. */
  67. public static void main(String[] args) {
  68. CheckCode codeVo = new CheckCode();
  69. codeVo.Input();
  70. }
  71. }

运行结果:

请输入一个12位的数字。。。。。。
111111111111
checkCode = 6

发表评论

表情:
评论列表 (有 0 条评论,326人围观)

还没有评论,来说两句吧...

相关阅读