繁体   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