将整数转换为数字数组

75

我尝试将一个整数转换成一个数组。例如,将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: 针对字符串的输入:“”
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

我该如何解决这个问题?


1
Integer.toString(n).chars().map(a->a-'0').toArray(); - David S Alderson
增加了对负数值的支持,请查看下面的答案(针对新开发人员,因为已经过去8年了) - Phil
26个回答

1

您不必使用 substring(...)。使用 temp.charAt(i) 获取数字,并使用以下代码将 char 转换为 int

char c = '7';
int i = c - '0';
System.out.println(i);

1

调用这个函数:

  public int[] convertToArray(int number) {
    int i = 0;
    int length = (int) Math.log10(number);
    int divisor = (int) Math.pow(10, length);
    int temp[] = new int[length + 1];

    while (number != 0) {
        temp[i] = number / divisor;
        if (i < length) {
            ++i;
        }
        number = number % divisor;
        if (i != 0) {
            divisor = divisor / 10;
        }
    }
    return temp;
}

0

首先从用户输入整数,将其转换为String,并创建一个大小为str.length()的字符数组。现在使用charAt()方法通过for循环填充字符数组。

Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String str = Integer.toString(num);
char [] ch = new char [str.length()];

for(int i=0; i<str.length(); i++)
{
    ch[i] = str.charAt(i);
}

for(char c: ch)
{
    System.out.print(c +" ");
}

0

使用:

int count = 0;
String newString = n + "";
char [] stringArray = newString.toCharArray();
int [] intArray = new int[stringArray.length];
for (char i : stringArray) {
  int m = Character.getNumericValue(i);
  intArray[count] = m;
  count += 1;
}
return intArray;

你需要将这个放进一个方法里。


当你回答问题时,请尽量包含一个完整的可工作代码示例。在某些情况下,提问者可能不清楚可能解决方案的工作方式,因此提供一个代码示例,他们可能需要进行故障排除才能应用它,这可能会令人沮丧和更加困惑。在这种情况下,原始问题已经有近6年的历史,并且已经有一个被接受的答案。如果可以的话,请尝试查看未回答的问题,并查看是否有任何问题需要您的帮助。 - Stephen R. Smith

0
我可以建议以下方法:
将数字转换为字符串→将字符串转换为字符数组→将字符数组转换为整数数组
这是我的代码:
public class test {

    public static void main(String[] args) {

        int num1 = 123456; // Example 1
        int num2 = 89786775; // Example 2

        String str1 = Integer.toString(num1); // Converts num1 into String
        String str2 = Integer.toString(num2); // Converts num2 into String

        char[] ch1 = str1.toCharArray(); // Gets str1 into an array of char
        char[] ch2 = str2.toCharArray(); // Gets str2 into an array of char

        int[] t1 = new int[ch1.length]; // Defines t1 for bringing ch1 into it
        int[] t2 = new int[ch2.length]; // Defines t2 for bringing ch2 into it

        for(int i=0;i<ch1.length;i++) // Watch the ASCII table
            t1[i]= (int) ch1[i]-48; // ch1[i] is 48 units more than what we want

        for(int i=0;i<ch2.length;i++) // Watch the ASCII table
            t2[i]= (int) ch2[i]-48; // ch2[i] is 48 units more than what we want
        }
    }

0
在JavaScript中,这一行代码就可以解决问题:
Array.from(String(12345), Number);

例子

const numToSeparate = 12345;

const arrayOfDigits = Array.from(String(numToSeparate), Number);

console.log(arrayOfDigits);   //[1,2,3,4,5]

解释

1- String(numToSeparate) 将数字 12345 转换为字符串,返回 '12345'

2- Array.from() 方法从类似数组或可迭代对象创建一个新的数组实例,字符串 '12345' 是一个可迭代对象,因此它将创建一个数组。

3- 但在自动创建这个新数组的过程中,Array.from() 方法将首先将任何可迭代元素(在本例中是每个字符,例如:'1','2')传递给我们设置为第二个参数的函数,这个函数在本例中为 Number 函数。

4- Number 函数将获取任何字符串字符并将其转换为数字,例如:Number('1');将返回 1

5- 这些数字将逐一添加到一个新数组中,最后将返回这个数字数组。

总结

这行代码 Array.from(String(numToSeparate), Number); 将数字转换为字符串,取出该字符串的每个字符,将其转换为数字并放入新数组中。最终,这个由数字组成的新数组将被返回。


3
那是JS,问题被标记为Java。 - Inmer

0

不使用 String、Integer、ArrayList、Math:

// Actual number
int n = 56715380;
            
            // Copy of the number
            int m = n;
            
            // Find no. of digits as length
            int ln = 0;
            while (m > 0) {
                m = m / 10;
                ln++;
            }
            
            // Copy of the length
            int len = ln;
    
            // Reverse the number
            int revNum = 0;
            ln--;
            int base;
            while (n > 0) {
                base = 1;
                for (int i = 0; i < ln; i++) {
                    base = base * 10;
                }
                revNum = revNum + base * (n % 10);
                n = n / 10;
                ln--;
            }
    
            // Store the reverse number in the array
            int arr[] = new int[len];
            for (int i = 0; revNum > 0; i++) {
                arr[i] = revNum % 10;
                revNum = revNum / 10;
            }
            
            // Print the array
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i]);
            }

0
这是一个函数,它接受一个整数并返回一个数字数组。
static int[] Int_to_array(int n)
{
    int j = 0;
    int len = Integer.toString(n).length();
    int[] arr = new int[len];
    while(n!=0)
    {
        arr[len-j-1] = n % 10;
        n = n / 10;
        j++;
    }
    return arr;
}

0
简单迭代
List<Integer> integerList = new ArrayList<>();
int remainder = 0;
while(n>0){
        remainder = n%10;
        n /=10;
    integerList.add(remainder);
}
int[] numArray = integerList.stream().mapToInt(x->x).toArray();

0

temp2 = temp.substring(i);总是返回空字符串""。

相反,您的循环应该有条件i<temp.length()。而且temp2应该始终是temp.substring(i, i+1);

同样地,当您打印出newGuess时,您应该循环到newGuess.length但不包括。所以您的条件应该是i<newGuess.length


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接