整数打印错误值

将整数转换为int数组时,例如123到{1,2,3},我得到值{49,50,51}。 无法找到我的代码有什么问题。

public class Test { public static void main(String [] args) { String temp = Integer.toString(123); int[] newGuess = new int[temp.length()]; for (int i = 0; i < temp.length(); i++) { newGuess[i] = temp.charAt(i); } for (int i : newGuess) { System.out.println(i); } } } 

输出:

49

50

51

charAt(i)将为您提供整数的UTF-16代码单位值,例如在您的情况下,UTF-16代码单位值1为49.要获得该值的整数表示,您可以减去’0’(UTF-来自i的16个代码单元值48)

 public class Test { public static void main(String [] args) { String temp = Integer.toString(123); int[] newGuess = new int[temp.length()]; for (int i = 0; i < temp.length(); i++) { newGuess[i] = temp.charAt(i); } for (int i : newGuess) { System.out.println(i - '0'); } } } 

输出:

1

2

3

temp.charAt(i)基本上是回归你的角色。 您需要从中提取Integer值。

您可以使用:

 newGuess[i] = Character.getNumericValue(temp.charAt(i)); 

产量

 1 2 3 

 public class Test { public static void main(String [] args) { String temp = Integer.toString(123); int[] newGuess = new int[temp.length()]; for (int i = 0; i < temp.length(); i++) { newGuess[i] = Character.getNumericValue(temp.charAt(i)); } for (int i : newGuess) { System.out.println(i); } } } 

要在混合中添加一些Java 8细节,这样我们可以整齐地打包所有内容,您可以选择:

 int i = 123; int[] nums = Arrays.stream(String.valueOf(i).split("")) .mapToInt(Integer::parseInt) .toArray(); 

这里我们得到一个流到一个字符串数组的流,这个字符串是通过拆分给定整数数字的字符串值而创建的。 然后,我们将这些整数值与Integer#parseInt映射到IntStream ,然后最终将其转换为数组。

因为你的兴趣是得到一个字符串的整数值。 使用方法parse int Integer.parseInt()。 这将返回整数。 示例:int x = Integer.parseInt(“6”); 它将返回整数6。