簡體   English   中英

多維數組上的數組長度

[英]array length on multidimensional arrays

對於以下代碼

public static void main(String[] args)
  {

  String[][] fruits = {{"orange", "pear", "banana", "pinapple" "grape"},
                     {"apple", "kiwi", "strawberry", "plum"}};

  String[] veggies = {"okra","pumpkin", "spinach", "brockoli"};


  System.out.println(fruits.length); 
  System.out.println(veggies.length);

  }  

System.out.println(veggies.length); 打印出 4 因為有 4 個元素。

System.out.println(fruits.length); 打印出來 2,為什么? 應該不是 9,因為有 9 個元素。

要打印多維 (n) 數組的長度,您應該使用 (n) 循環。

所以你應該使用:

String[][] fruits = {{"orange", "pear", "banana", "pinapple" "grape"},
                 {"apple", "kiwi", "strawberry", "plum"}};
int length = 0;
for(int i=0;i<fruits.length;i++){
  length += fruits[i].length;
 }
System.out.println(length);

fruits ,就像你說的,是一個多維數組,或者只是一個數組數組。 在你給出的例子中,fruits 里面有 2 個數組,因此他的長度是 2。
如果你想知道有多少“成果”都在里面,我建議你總結里面每個數組的長度fruits

fruits.length只為您提供水果中存儲的元素數量。 那是多少? 只有兩個。 水果包含兩個元素。 它們恰好是包含其他項目的數組:

{"orange", "pear", "banana", "pinapple" "grape"}
{"apple", "kiwi", "strawberry", "plum"}

因此,要獲取每個數組的長度:

fruits[0].length
fruits[1].length

Fruits 是一個二維數組,fruits.length 只給你第一維的長度。

水果[0].長度+水果[1].長度會給你9然后

這是因為fruits在該數組中存儲了兩個數組,第一個長度為 5,第二個長度為 4。如果您只是調用:

System.out.println(fruits.length);

它將返回該數組(2 個數組)中對象的長度。

如果你想獲得中第一個數組的長度fruits ,你會打電話

System.out.println(fruits[0].length); ,

這將打印出 5. 如果你要打電話

System.out.println(fruits[1].length); ,

它將打印出 4。

因為, fruits是一個二維數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM