开发者

how to get an array of of the digits of an int in java

So this probably would be easy if done like this

public static [] nums(int j)
{
    int num = 12345;
    int[]thenums = [5];

    for(int i=0; i<5; i++)
    {
       thenums[4-i] = num%10;
       num = num/10;
    }

return the nums
}

i get {1,2,3,4,5}

but for some reason if the numb开发者_JS百科er starts with a 0 then it does not work how to make this work if the number were

int num = 02141;

thanks


EDIT: Doh... I'd completely forgotten about octal literals. That explains why the value is showing up differently. (02141 is treated as an octal literal; it's not the same value as 2141.)

However, it sounds like the OP wants to "remember" the number of leading zeroes in a number. There's no way of doing that as an integer, because it's just remembering a value. What's the difference between seeing "3" birds and seeing "0000003" birds?

If you have a number representation where the leading zeroes are important, you're not just talking about an integer quantity, which is all that an int represents.

Where are you getting your input from? It sounds like you should just be maintaining it as a string from the start.

If you always want 5 digits, that's easy to do - and your current code should do it (when amended to actually compile) - something like this:

public class Test
{
    public static void main(String[] args) 
    {
        int[] digits = getDigits(123);
        for (int digit : digits)
        {
            System.out.print(digit); // Prints 00123
        }
    }

    public static int[] getDigits(int value)
    {
        int[] ret = new int[5];
        for (int i = 4; i >=0 ; i--)
        {
            ret[i] = value % 10;
            value = value / 10;
        }
        return ret;
    }
}

Now that's hard-coded to return 5 digits. If you don't know the number of digits at compile-time, but you will know it at execution time, you could pass it into the method:

public static int[] getDigits(int value, int size)
{
    int[] ret = new int[size];
    for (int i = size - 1; i >=0 ; i--)
    {
        ret[i] = value % 10;
        value = value / 10;
    }
    // Perhaps throw an exception here if value is not 0? That would indicate
    // we haven't captured the complete number

    return ret;
}


What happens in your code is that 02141 is not the same as 2141; the first is octal (equivalent to 1121 decimal), while the second is 2141 decimal.

The relevant part of the Java Language Specification is JLS 3.10.1, specifically the grammar productions for DecimalNumeral and OctalNumeral.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜