将整数转换为数字数组 [英] Convert an integer to an array of digits
问题描述
我尝试将整数转换为数组.例如,从1234到int[] arr = {1,2,3,4};
.
I try to convert an integer to an array. For example, 1234 to int[] arr = {1,2,3,4};
.
我已经写了一个函数:
public static void convertInt2Array(int guess) {
String temp = Integer.toString(guess);
String temp2;
int temp3;
int [] newGuess = new int[temp.length()];
for(int i=0; i<=temp.length(); i++) {
if (i!=temp.length()) {
temp2 = temp.substring(i, i+1);
} else {
temp2 = temp.substring(i);
//System.out.println(i);
}
temp3 = Integer.parseInt(temp2);
newGuess[i] = temp3;
}
for(int i=0; i<=newGuess.length; i++) {
System.out.println(newGuess[i]);
}
}
但是会引发异常:
线程"main"中的异常; java.lang.NumberFormatException:对于输入字符串:
在java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
在java.lang.Integer.parseInt(Integer.java:504)
在java.lang.Integer.parseInt(Integer.java:527)
在q4.test.convertInt2Array(test.java:28)
在q4.test.main(test.java:14)
Java结果:1
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at q4.test.convertInt2Array(test.java:28)
at q4.test.main(test.java:14)
Java Result: 1
我该如何解决?
推荐答案
直接的问题是由于您使用<= temp.length()
而不是< temp.length()
.但是,您可以更简单地实现这一目标.即使您使用字符串方法,也可以使用:
The immediate problem is due to you using <= temp.length()
instead of < temp.length()
. However, you can achieve this a lot more simply. Even if you use the string approach, you can use:
String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
在打印内容时也需要进行相同的更改以使用< newGuess.length()
-否则对于长度为4的数组(其有效索引为0、1、2、3),您将尝试使用for
循环在条件下使用<
,而不是<=
.
You need to make the same change to use < newGuess.length()
when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]
. The vast majority of for
loops I write use <
in the condition, rather than <=
.
这篇关于将整数转换为数字数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!