2016-09-14 93 views
1

将整数转换为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); 
     } 
    } 
} 

输出:

+0

[在Java中将整数转换为int数组]可能的副本(http://stackoverflow.com/questions/39482457/converting-an-integer-into-an-int-array-in-java) –

回答

4

charAt(i)会给整数你UTF-16码单位值例如在您的情况,UTF-16代码单元值为1是49. 要获得该值的整数表示,可以从减去'0'(UTF-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

是迂腐的,'charAt'不返回ASCII值,而是'char'值,它们是UTF-16代码单元。恰巧,前128个字符是相同的,其中包括普通的拉丁字母。但Java从来没有使用过ASCII字符串,从第一天开始它就是Unicode。根据您的评论编辑 –

+0

。感谢您的信息。:) – Batty

1

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); 
     } 
    } 
} 
0

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

+0

'Integer.parseInt(“123”)'将返回整数'123',而不是'{1,2,3}'int数组。 – Batty

1

要一点点的Java 8细微增加,使我们能够收拾整齐了一切的搭配,你可以选择做:

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

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