2017-04-10 31 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