[英]How to get the digits of an integer and store it into an array? [Java]
[英]how to get an array of of the digits of an int in java
因此,如果这样做,这可能会很容易
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
}
我得到{1,2,3,4,5}
但是由于某种原因,如果数字以0开头,那么如果数字为
int num = 02141;
谢谢
编辑:......我完全忘记了八进制文字。 这就解释了为什么值显示不同。 ( 02141
被视为八进制文字;它的值与2141
。)
但是,听起来OP希望“记住”数字中的前导零。 无法将其作为整数来执行,因为它只是记住一个值。 看到“ 3”只鸟和看到“ 0000003”只鸟有什么区别?
如果您有一个数字表示形式,其中前导零很重要,那么您不仅在谈论整数,而整数就是int
表示的全部。
您从哪里得到您的意见? 听起来您应该从一开始就将其维护为字符串。
如果您总是想要5位数字,那很容易-您的当前代码应该做到这一点(在修改为实际编译时)-如下所示:
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;
}
}
现在,将其硬编码为返回5位数字。 如果你不知道在编译时的位数,但你会知道它在执行时,你可以通过它进入方法:
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;
}
您的代码中发生的是02141
与2141
; 第一个是八进制的(相当于1121
十进制),而第二个是2141
十进制。
Java语言规范的相关部分是JLS 3.10.1 ,特别是DecimalNumeral
和OctalNumeral
的语法生成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.