如何将Java整数转换为Int数组实例

572 阅读2分钟

要把Integerint 类型的数据转换成int[] 数组类型,你需要做以下步骤。

  • 首先,将你的Integerint 转换为一个String
  • 然后创建一个新的int[] 实例,用String.length() 方法的值作为数组的大小
  • 使用一个for 循环,将每个String 字符放入数组中

让我们看看将一个int 的值转换成一个int[] 的例子。

首先,使用Integer.toString() 方法创建一个int 类型的String 表示:

public static void main(String[] args)
{
int num = 12345;
String temp = Integer.toString(num);
}

然后,创建一个新的int[] ,稍后你将把整数放在那里。

使用String.length() 方法来确定数组的大小:

public static void main(String[] args)
{
int num = 12345;
String temp = Integer.toString(num);
int[] numbers = new int[temp.length()];
}

最后,创建一个for 循环,遍历String ,并将String 里面的每个字符分配到数组中。

看一下下面的代码:

for (int i = 0; i < temp.length(); i++) {
numbers[i] = Character.getNumericValue(temp.charAt(i));
}

你需要使用Character.getNumericalValue()String.charAt() 方法的组合来获得正确的整数值。

这是因为String.charAt() 方法将数字作为String ,而你不使用Character.getNumericalValue() 方法就能得到数字的Unicode值。

下面的代码显示了只调用charAt() 方法的结果:

for (int i = 0; i < temp.length(); i++) {
numbers[i] = temp.charAt(i);
}
System.out.println("Variable numbers content: " + Arrays.toString(numbers));
// Variable numbers content: [49, 50, 51, 52, 53]

这就是为什么你需要用getNumericalValue() 方法包住charAt() 方法返回的值。

下面是使用Java将int 转换为int[] 的完整代码:

public static void main(String[] args)
{
int num = 12345;
String temp = Integer.toString(num);
int[] numbers = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
numbers[i] = Character.getNumericValue(temp.charAt(i));
}
System.out.println("Variable numbers type: "
+ numbers.getClass().getSimpleName());
// Variable numbers type: int[]

System.out.println("Variable numbers content: "
+ Arrays.toString(numbers));
// Variable numbers content: [1, 2, 3, 4, 5]
}

请根据你的需要自由修改上面的代码😉: