gpt4 book ai didi

java - 将整数转换为数字数组

转载 作者:IT老高 更新时间:2023-10-28 20:50:31 26 4
gpt4 key购买 nike

我尝试将整数转换为数组。例如,1234 到 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]);
}
}

但是抛出异常:

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() .但是,您可以更简单地实现这一点。即使你使用字符串方法,你也可以使用:

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),您将尝试使用 newGuess[4] .绝大多数for我写的循环使用 <在条件下,而不是 <= .

关于java - 将整数转换为数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8033550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com