數據加載中……
          二維數組的使用

          Java中,二維數組的定義和一維數組是一樣的。

          public class Welcome {

               public static void main(String[] args) {

                  int [][] num;

                  num=new int[3][4];

                  num[0][1]=1;

                  num[1][3]=12;

                  num[2][2]=21;        

                      }

          }

          Java中二維數組的列數可以不同,比如第一行是2列,第二行是4列,等等。

          有些類似與c語言中的指針數組。

          public class Welcome {

               public static void main(String[] args) {

                   int [][] num;

                  num=new int[3][];

                  num[0]=new int[2];

                  num[1]=new int[4];

                  num[2]=new int[3];

                  num[0][1]=12;

                  num[1][3]=23;

                  num[2][2]=34;

                  System.out.println(num[0][1]);

                  System.out.println(num[1][3]);

                  System.out.println(num[2][2]);

                      }

           }

          在java中沒有定義的自動賦值為0.

          在定義時可以為二維數組來定義,但是在賦初值時 ,不要在定義大小了

          int [][] num=new int[3][]{1,2,3,4,5,2,3,4,5,6} //error

          public class Welcome {

               public static void main(String[] args) {

                   int [][] num=new int[][]{1,2,3,4,5,2,3,4,5,6}; //error

                   int [][] num=new int[][]{{1,2,3,4,5},{2,3,4,5,6}}; //ok    

                  }

          }

          定義二維數組還有一種方式

          public class Welcome {

               public static void main(String[] args) {

                     int [][] num={1,2,3,4,5,2,3,4,5,6}; //error

                   }

          }

          也可以定義不規則的二維數組

          public class Welcome {

               public static void main(String[] args) {

                   int [][] num={{1,2,3},{4,5},{2}};

                  System.out.println(num[0][2]);

                  System.out.println(num[1][1]);

                  System.out.println(num[2][0]);

                   }

          }

          posted on 2008-02-28 11:00 rick 閱讀(3339) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 黎川县| 博湖县| 华阴市| 长春市| 津南区| 新兴县| 天峻县| 连城县| 隆昌县| 吐鲁番市| 磴口县| 临沂市| 林芝县| 周至县| 新竹县| 乌鲁木齐市| 彰化县| 都安| 桂林市| 宜昌市| 宁海县| 共和县| 全州县| 宿迁市| 凯里市| 和林格尔县| 琼中| 漯河市| 拉孜县| 沭阳县| 墨脱县| 永济市| 江陵县| 弥勒县| 延寿县| 海安县| 永兴县| 德保县| 祥云县| 惠水县| 思南县|