我一直在研究一个扁平3D维阵列的代码段,但是我遇到了一个令人困惑的情况,使用下面的代码。
使用的数组初始化如下:
int array[][][] = {
{
{000, 001, 002},
{010, 011, 012},
{020, 021, 022},
},
{
{100, 101, 102},
{110, 111, 112},
{120, 121, 122},
},
{
{200, 201, 202},
{210, 211, 212},
{220, 221, 222},
}
};
然后通过基本的嵌套for循环输出数组。 输出通过自定义DecimalFormat格式化,允许我打印浮动0#。
DecimalFormat xFormat = new DecimalFormat("000");
for(int z = 0; z < array[0].length; z++) {
for(int y = 0; y < array[1].length; y++) {
for(int x = 0; x < array[2].length; x++) {
System.out.println("I = "+ i + " Element at i = " + xFormat.format(array[z][y][x]));
}
}
}
这个循环在数组初始化后立即使用,但输出完全令我困惑
I = 0 Element at i = 000
I = 1 Element at i = 001
I = 2 Element at i = 002
I = 3 Element at i = 008 <------- =/= 010
I = 4 Element at i = 009 <------- =/= 011
I = 5 Element at i = 010 <------- =/= 012
I = 6 Element at i = 016 <------- =/= 020
I = 7 Element at i = 017 <------- =/= 021
I = 8 Element at i = 018 <------- =/= 022
I = 9 Element at i = 100
I = 10 Element at i = 101
I = 11 Element at i = 102
I = 12 Element at i = 110
I = 13 Element at i = 111
I = 14 Element at i = 112
I = 15 Element at i = 120
I = 16 Element at i = 121
I = 17 Element at i = 122
I = 18 Element at i = 200
I = 19 Element at i = 201
I = 20 Element at i = 202
I = 21 Element at i = 210
I = 22 Element at i = 211
I = 23 Element at i = 212
I = 24 Element at i = 220
I = 25 Element at i = 221
I = 26 Element at i = 222
这对我来说似乎相当原始,但我不确定此时我缺少什么。大部分循环打印出正确,但它的中间部分没有正确输出,并且对多维数组问题的搜索没有产生很多解决方案
答案 0 :(得分:0)
因为0*
(0前缀)用于存储八进制数字(base8)
{000, 001, 002}, //0,1,2
{010, 011, 012}, //8,9,10
{020, 021, 022}, //16,17,18
swhy 010转换为8十进制,11到9等等。就像0x*
用于存储十六进制,aod ***b
来存储二进制文件。 DecimalFormat
获得八进制 010的值,等于9,这就是你在输出中得到的结果。
其余的值是小数,因为它们不以0开头。你可以为每个其他walue加上前缀0,看看会发生什么。