Java菜鳥學習筆記--數組篇(三):二維數組__Java

來源:互聯網
上載者:User
定義

//1.二維數組的定義//2.二維數組的記憶體空間//3.不規則數組package me.array;public class Array2Demo{public static void main(String[] args){//定義二維數組int[ ] [ ] arr={{1,2,3},{4,5,6}};//靜態初始化 //列印出二維數組for(int i=0;i<arr.length;i++){for(int j=0;j<arr[i].length;j++){System.out.print(arr[i][j]+" ");}//輸出一列後就斷行符號空格System.out.println();}}}


二維數組記憶體結構

(圖片著作權歸“良葛格的JAVA學習筆記”所有)




不規則二維數組


//1.二維數組的定義//2.二維數組的記憶體空間//3.不規則數組package me.array;public class Array2Demo{public static void main(String[] args){//建立和列印不規則二維數組int arr[ ][ ];arr=new int[3][];//現在說明為不規則數組arr[0]=new int[10];//arr[0]指向另一個一位元組arr[1]=new int[3];arr[2]=new int[4];//賦值for(int i=0;i<arr.length;i++){for(int j=0;j<arr[i].length;j++){arr[i][j]=j;}}//輸出for(int i=0;i<arr.length;i++){for(int j=0;j<arr[i].length;j++){System.out.print(arr[i][j]+" ");}System.out.println();}/*輸出結果:0 1 2 3 4 5 6 7 8 9 0 1 2 0 1 2 3 *///}}



//3.編寫一個方法,返回double型二維數組,數組通過解析字串參數獲得。//如"1,2;3,4,5;6,7,8"//d[0,0]=1.0 d[0,1]=2.0 d[1,0]=3.0 ....package me.parser;public class TestString{public static void main(String[] args){//1.用字串分解split(";")成三個字串數組//2.再分解split(",")//聲明一個二維數組用來裝分解好的字元String s="1,2;3,4,5;6,7,8";//以split()方法 分解String[] sFirst=s.split(";");String[][] word=new String[sFirst.length][];int flag=0;for(int i=0;i<sFirst.length;i++){//列印出已經分開的//System.out.println(sFirst[i]);/*這條語句輸出1,23,4,56,7,8*///接下來在按照 ,分開他們放入一個一維數組String[] sSecond=sFirst[i].split(","); //~ System.out.println(sSecond.length);//~ /*輸出://~ 2//~ ---------------------------------//~ 3//~ ---------------------------------//~ 3//~ ---------------------------------//~ *///說明每次sSencond這個一維數組的長度不同word[i]=new String[sSecond.length];//這步確定行不規則數組的每行長度//為這個數組賦值for(int j=0;j<sSecond.length;j++){word[i][j]=sSecond[j];}System.out.println("---------------這是第"+(i+1)+"次迴圈-------------------");}//輸出二維數組System.out.println("輸出二維數組-------------------");for(int i=0;i<word.length;i++){for(int j=0;j<word[i].length;j++){System.out.print(word[i][j]+" ");}System.out.println();}/*結果:---------------這是第1次迴圈----------------------------------這是第2次迴圈----------------------------------這是第3次迴圈-------------------輸出二維數組-------------------1 2 3 4 5 6 7 8 輸出二維數組-------------------*///}}



作者:YangGan
出處:http://blog.csdn.net/incyanggan
本文基於署名 2.5 中國大陸許可協議發布,歡迎轉載,演繹或用於商業目的,但是必須保留本文的署名Yanggan(包含連結).


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.