将整数转换为 Java 中的 int 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39482457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:11:10  来源:igfitidea点击:

Converting an integer into an int array in Java

java

提问by Ron

I am very new to Java programming and was wondering if there is a way to convert an integer into an int array. The reason I ask is because I know it is possible to convert an integer into a String so I was hoping there was other shortcuts for me to learn as well.

我对 Java 编程很陌生,想知道是否有办法将整数转换为 int 数组。我问的原因是因为我知道可以将整数转换为字符串,所以我希望还有其他快捷方式可供我学习。

An example of what I am trying to do is taking int 10382 and turning it into int array {1, 0, 3, 8, 2}

我想要做的一个例子是将 int 10382 转换为 int array {1, 0, 3, 8, 2}

Any help or guidance will be much appreciated, thank you very much.

任何帮助或指导将不胜感激,非常感谢。

采纳答案by lxnx

Java 8 Stream API

Java 8 流 API

int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();

Source : stackoverflow

来源:stackoverflow

回答by Dev. Joel

You can convert entire string and then you get the toCharArraymethod separately characters in an array

您可以转换整个字符串,然后toCharArray在数组中分别获取该方法的字符

Scanner t = new Scanner(System.in);
     int x = t.nextInt();
     char[] xd = String.valueOf(x).toCharArray();

    for (int i = 0; i < xd.length; i++) {
        System.out.println(xd[i]);
    }

Another way of doing this would be:

另一种方法是:

int test = 12345;
        int[] testArray = new int[String.valueOf(test).length()];

And then looping over it.

然后循环过去。

回答by bhanu avinash

int x = 10382;
String[] str1 = Integer.toString(x).split("");

for(int i=0;i<str1.length;i++){
    System.out.println(str1[i]);
}