将整数转换为数字数组

编程入门 行业动态 更新时间:2024-10-08 19:39:25
本文介绍了将整数转换为数字数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试将整数转换为数组.例如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

我该如何解决这个问题?

How can I fix this?

推荐答案

当前的问题是由于您使用了 <= 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)的数组,您将尝试使用 newGuess[4].我编写的绝大多数 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 <=.

更多推荐

将整数转换为数字数组

本文发布于:2023-11-30 18:25:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651059.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数组   转换为   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!