问题
How can I store 08 and 09 into an int array? I understand that they cannot due to binary characteristics and have tried both...
0b08, 0b09 ... and ... 0B08, 0B09 with no luck.
The following line of code is ideally what I'd like to have:
final int[] monthValidDosInputs = {00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12};
Here is the error...
ConvertDate.java:15: error: integer number too large: 08
ConvertDate.java:15: error: integer number too large: 09
Thanks!
回答1:
When you start a literal integer with 0
, it's considered an octal number, one that uses base 8 rather than base 10. That means 8
and 9
are not valid digits.
If you really want a leading zero (i.e., octal), you would need something like:
int[] monthValidDosInputs = {000, 001, ..., 007, 010, 011, 012, 013, 014};
which gives you the decimal numbers 0
through 12
, but in octal.
However, if you want to keep them evenly spaced with decimal, just use a leading space instead of zero:
int[] monthValidDosInputs = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^
although I'm not sure you gain anything from that. You may as well just use:
int[] monthValidDosInputs = {0,1,2,3,4,5,6,7,8,9,10,11,12};
and be done with it. It makes no difference to the compiler.
If you're looking to use these to check user input (where they may enter 8
or 08
for a month), you're better off either:
- using strings to check against; or
- reducing their input to an integer (using something like
Integer.parseInt(str,10)
) so that there's no difference between04
and4
.
回答2:
dystroy is right, store them as strings in a String[]
array and then parse them to int
when you want to use them as integers.
回答3:
There is no way I know of that you can hold those values in and int[] array. Instead use String[] array and convert to int values if needed.
来源:https://stackoverflow.com/questions/23211146/java-using-08-and-09-in-an-array