将整数转换为数字数组

时间:2011-11-07 06:57:43

标签: java integer

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

有任何想法吗?

24 个答案:

答案 0 :(得分:51)

直接问题是由于您使用<= 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循环在条件中使用<,而不是<=

答案 1 :(得分:39)

您不需要将int转换为String,只需使用% 10获取最后一位数字,然后将您的int除以10即可转到下一位数。

int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
    array.add(temp % 10);
    temp /= 10;
} while  (temp > 0);

这将使您的ArrayList以相反的顺序包含您的数字。如果需要,您可以轻松还原它并将其转换为int []。

答案 2 :(得分:24)

public static void main(String[] args)
{
    int num = 1234567;  
    int[]digits = Integer.toString(num).chars().map(c -> c-'0').toArray();  
    for(int d : digits)
        System.out.print(d);    
}

主要想法是

  1. 将int转换为其String值
  2. Integer.toString(num);
    
    1. 获取一个int流,表示构成整数的String版本的每个char(~data)的ASCII值
    2. Integer.toString(num).chars();
      
      1. 将每个char的ascii值转换为其值。 要获取char的实际int值,我们必须从实际char的ASCII代码中减去char'0'的ASCII代码值。 要获取我们数字的所有数字,必须在每个字符(对应于数字)上应用此操作,组成与我们的数字相当的字符串,这通过将下面的地图函数应用于我们的IntStream来完成。
      2. Integer.toString(num).chars().map(c -> c-'0');
        
        1. 使用toArray()
        2. 将int流转换为int数组
          Integer.toString(num).chars().map(c -> c-'0').toArray();
          

答案 3 :(得分:3)

在 Javascript 中,这一行就可以解决问题:

Dictionary<string, string> postUrl = new Dictionary<string, string>()
{
    { "endpoint", "http://127.0.0.1:8000"},
    { "resource", "auth/login"},
    { "paramaters", ""},
    { "key", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlY2hpZUBlbWFpbC5jb20iLCJwYXNzd29yZCI6InRlY2hpZSIsImlhdCI6MTYxMDYzNjYzNywiZXhwIjoxNjEwNjQwMjM3fQ.CW6adTp9PNT3oTiQVKSy3HHYZMimUM12V5aWUiyDPoc"}
};

示例

Array.from(String(12345), Number);

说明

1- const numToSeparate = 12345; const arrayOfDigits = Array.from(String(numToSeparate), Number); console.log(arrayOfDigits); //[1,2,3,4,5] 将数字 12345 转换为字符串,返回 '12345'

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

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

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

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

总结

代码行 1 将把数字转换成一个字符串,取该字符串的每个字符,将其转换成一个数字并放入一个新数组中。最后,将返回这个新的数字数组。

答案 4 :(得分:2)

使用String.split方法

会更简单
public static void fn(int guess) {
    String[] sNums = Integer.toString(guess).split("");
    for (String s : nums) {
    ...

答案 5 :(得分:2)

在Scala中,您可以这样做:

def convert(a: Int, acc: List[Int] = Nil): List[Int] =
  if (a > 0) convert(a / 10, a % 10 +: acc) else acc

在一行中且没有撤销订单。

答案 6 :(得分:2)

您可以使用 -

private int[] createArrayFromNumber(int number) {
    String str = (new Integer(number)).toString();
    char[] chArr = str.toCharArray();
    int[] arr = new int[chArr.length];
    for (int i = 0; i< chArr.length; i++) {
        arr[i] = Character.getNumericValue(chArr[i]);
    }
    return arr;
}

答案 7 :(得分:2)

你可以这样做:

char[] digits = string.toCharArray();

然后你可以将字符评估为整数: 例如:

char[] digits = "12345".toCharArray();
int digit = Character.getNumericValue(digits[0]);
System.out.println(digit); // prints 1

答案 8 :(得分:1)

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

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

答案 9 :(得分:1)

尝试一下!


int num = 1234; 

String s = Integer.toString(num); 

int[] intArray = new int[s.length()]; 


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

答案 10 :(得分:1)

您可以执行以下操作

public int[] convertDigitsToArray(int n) {

    int [] temp = new int[String.valueOf(n).length()]; //calculate the length of digits
    int i = String.valueOf(n).length()-1 ;  //initialize the value to the last index
    do {
        temp[i]= n%10;
        n = n/10;
        i--;
    }while(n>0);
    return temp;
}

这还将保持顺序。

如果有帮助,请回复。

答案 11 :(得分:0)

不使用字符串、整数、数组列表、数学:

// 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]);
            }

答案 12 :(得分:0)

temp2 = temp.substring(i);将始终返回空字符串“”。

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

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

答案 13 :(得分:0)

让我们使用递归来解决...

ArrayList<Integer> al = new ArrayList<>();
void intToArray(int num){
    if( num != 0){
        int temp = num %10;
        num /= 10;
        intToArray(num);
        al.add(temp);
    }
}

说明:  假设num = 12345。

在第一次调用函数temp时保持值:5,num的值=1234。再次传递给函数,现在temp保持值:4,num = 123的值。 num不等于0。

StackTrace:

 temp - 5 | num - 1234
 temp - 4 | num - 123
 temp - 3 | num - 12
 temp - 2 | num - 1
 temp - 1 | num - 0

 And then, It calls add method of ArrayList and value of temp is added to it, so value of list:
 ArrayList - 1
 ArrayList - 1,2
 ArrayList - 1,2,3
 ArrayList - 1,2,3,4
 ArrayList - 1,2,3,4,5

我希望可以使用递归清除您的疑问。

答案 14 :(得分:0)

首先将用户输入作为int,然后将其转换为String,然后创建一个大小为str.length()的字符数组,现在使用charAt()填充for循环的char数组。

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 +" ");
}

答案 15 :(得分: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;
}

答案 16 :(得分:0)

我无法为Vladimir解决方案添加评论,但我认为当您的初始数字也低于10时,这也会更有效。 这是我的建议:

int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
  array.add(temp % 10);
  temp /= 10;
} while  (temp > 1);

请记住反转数组。

答案 17 :(得分: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;

兄弟告诉我这是否有效。你必须把它放到我儿子的方法中。

答案 18 :(得分:0)

我可以建议以下方法:

  

将数字转换为字符串 - &gt;将字符串转换为字符数组 - &gt;将字符数组转换为整数数组

我的代码来了:

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
    }
}

答案 19 :(得分:0)

调用这些功能

  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;
}

答案 20 :(得分:0)

for语句中的<=应为<

BTW,可以在不使用字符串的情况下更有效地执行此操作,而是使用整数的/10%10

_

答案 21 :(得分:-1)

我不能在弗拉基米尔的决定中添加评论,但是您可以立即使阵列以正确的方向部署。这是我的解决方案:

public static int[] splitAnIntegerIntoAnArrayOfNumbers (int a) {
    int temp = a;
    ArrayList<Integer> array = new ArrayList<Integer>();
    do{
        array.add(temp % 10);
        temp /= 10;
    } while  (temp > 0);
    int[] arrayOfNumbers = new int[array.size()];
    for(int i = 0, j = array.size()-1; i < array.size(); i++,j--) 
        arrayOfNumbers [j] = array.get(i);
    return arrayOfNumbers;
}

重要提示:此解决方案不适用于负整数。

答案 22 :(得分:-1)

我修改了Jon Skeet's accepted answer,因为它不接受负值。

现在,它可以接受并转换数字:

public static void main(String[] args) {
    int number = -1203;
    boolean isNegative = false;
    String temp = Integer.toString(number);

    if(temp.charAt(0)== '-') {
        isNegative = true;
    }
    int len = temp.length();
    if(isNegative) {
        len = len - 1;
    }
    int[] myArr = new int[len];

    for (int i = 0; i < len; i++) {
        if (isNegative) {
            myArr[i] = temp.charAt(i + 1) - '0';
        }
        if(!isNegative) {
            myArr[i] = temp.charAt(i) - '0';
        }
    }

    if (isNegative) {
        for (int i = 0; i < len; i++) {
            myArr[i] = myArr[i] * (-1);
        }
    }

    for (int k : myArr) {
        System.out.println(k);
    }
}

输出

-1
-2
0
-3

答案 23 :(得分:-2)

public static void main(String k[])
{  
    System.out.println ("NUMBER OF VALUES ="+k.length);
    int arrymy[]=new int[k.length];
    for (int i = 0; i < k.length; i++)
    {
        int newGues = Integer.parseInt(k[i]);
        arrymy[i] = newGues;
    }
}