如何使用小于等于for循环在java中构建数组
我如何才能真正知道数量数组已经构建,而不是从索引中如何使用小于等于for循环在java中构建数组,java,Java,我如何才能真正知道数量数组已经构建,而不是从索引中 Java中的数组索引从0开始。因此,如果rd_1有12个元素,那么您可以将rd_1[0]寻址到rd_1[11] 因此,您的for循环应为 for(int i=0;i
Java中的数组索引从0开始。因此,如果
rd_1
有12个元素,那么您可以将rd_1[0]
寻址到rd_1[11]
因此,您的for
循环应为
for(int i=0;i
rd_1[i]=i+1代码>和i从0开始李>
下面两行例示了给定长度为12的数组。在这一行之后,数组有12个索引,其值为null
int array_quantity = 12;
int rd_1[] = new int[array_quantity];
长度固定为实例化数组时定义的长度,不能更改。如果您想知道实际设置的值的数量,必须按如下方式计算:
int array_quantity = 12;
int rd_1[] = new int[array_quantity];
计数器
然后保存设置的值量获取代码片段,这将是输出,这意味着Java中提到的其他数组从索引0开始,因此如果不使用它,它将为零
int counter = 0;
for (int i : rd_1) {
counter++;
}
因此,正确的代码片段如下所示
// If you get the value of 0 index it will be 0
System.out.println("rd_1[0] :- "+ rd_1[0]);
//Output :- rd_1[0] :- 0
// If you get the value of 11 index it will be 11
System.out.println("rd_1[11] :- "+ rd_1[11]);
//Output :- rd_1[11] :- 11
// If you get the value of 11 index it will be 11
System.out.println("rd_1[12] :- "+ rd_1[12]);
//Output :- Exception ArrayIndexOutOfBoundsException because Array will have 0 to 11 index, 12index will not be there
publicstaticvoidloop\u array\u build1()
{
int数组_数量=12;
int rd_1[]=新int[数组_数量];
对于(inti=0;我不清楚你问什么。。。
int counter = 0;
for (int i : rd_1) {
counter++;
}
// If you get the value of 0 index it will be 0
System.out.println("rd_1[0] :- "+ rd_1[0]);
//Output :- rd_1[0] :- 0
// If you get the value of 11 index it will be 11
System.out.println("rd_1[11] :- "+ rd_1[11]);
//Output :- rd_1[11] :- 11
// If you get the value of 11 index it will be 11
System.out.println("rd_1[12] :- "+ rd_1[12]);
//Output :- Exception ArrayIndexOutOfBoundsException because Array will have 0 to 11 index, 12index will not be there
public static void loop_array_build1()
{
int array_quantity = 12;
int rd_1[] = new int[array_quantity];
for(int i=0;i<array_quantity;i++)//Building
{
rd_1[i] = i+1;
System.out.println("Array building : rd_1["+i+"] -- "+rd_1[i]);
}
}
Array building : rd_1[0] -- 1
Array building : rd_1[1] -- 2
Array building : rd_1[2] -- 3
Array building : rd_1[3] -- 4
Array building : rd_1[4] -- 5
Array building : rd_1[5] -- 6
Array building : rd_1[6] -- 7
Array building : rd_1[7] -- 8
Array building : rd_1[8] -- 9
Array building : rd_1[9] -- 10
Array building : rd_1[10] -- 11
Array building : rd_1[11] -- 12