2016-09-14 87 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,然後最終將其轉換爲數組。