2017-04-10 29 views
-1
public static void loop_array_build1() 
{ 
    int array_quantity = 12; 
    int rd_1[] = new int[array_quantity]; 
    //Building 
    for (int i = 1; i < array_quantity; i++) 
    { 
     rd_1[i] = i; 
     System.out.println("Array building : " + rd_1[i]); 
    } 

    System.out.println(""); 
    System.out.println("Total array built -> " + rd_1.length); 
    System.out.println(""); 

    //Showing 
    for (int x = 1; x <= rd_1.length; x++) 
    { 
     System.out.println("Array showing : " + x); 
    } 
} 
  1. 我不能使用小于和等于(= <),因为我想从1到建立直到12,但如果我使用比(<)
    偏少它不是错误如何使用小于和等于用于循环在Java来构建阵列

    for(int i = 1; i < array_quantity; i++) << Not error 
    for(int i = 1; i <= array_quantity; i++) << Error 
    

,或者有在0只能从1开始的数组索引,不是?

  • 当我打印该行System.out.println("Total array built -> " + rd_1.length);它显示阵列有12个,
    也许它从这些2线取决于

    int array_quantity = 12; 
    int rd_1[] = new int[array_quantity]; 
    

    我怎么能真正知道量阵列已经建立,而不是从索引。在Java中

  • +2

    我不清楚你问什么... –

    回答

    0

    数组索引从0开始所以,如果rd_1有12个元素,那么你就可以解决rd_1[0]rd_1[11]包容性。

    因此您for循环的形式应该

    for (int i = 0; i < rd_1.length; i++)

    0
    1. 的您无法从索引1到建立12因为数组索引从0因此指望0-11。如果你想这些索引到具有值1-12使用rd_1[i] = i+1;和我从0开始

    以下2行实例化与所述给定长度为12。这条线后,将阵列,所述阵列具有12存在索引值为null

    int array_quantity = 12; 
    int rd_1[] = new int[array_quantity]; 
    

    长度固定为您在实例化数组时所定义的值,且无法更改。如果你想知道哪些是实际设定的值的数量,你将不得不指望他们像这样:

    int counter = 0; 
        for (int i : rd_1) { 
         counter++; 
        } 
    

    counter然后保存这些设置

    0

    以你的片断,这将是值的量输出,这意味着在其他的Java数组上述指数从0开始,因此,如果你不使用它,将是零

    // 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