簡體   English   中英

整數打印錯誤值

[英]Integer printing wrong value

將整數轉換為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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM