Foreach 语句

语法

 for(type element:array){
     System.out.println(element);
 }

例子

 package ch05;
 ​
 import java.util.*;
 ​
 public class ch05 {
 ​
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         String [] myName=new String [] {"小明","小红","小刘"};
         for(int i=0;i<myName.length;i++)
         {
             System.out.println(myName[i]);
         }
         for(String name :myName) {
             System.out.println(name);
         }
     }
 ​
 }

弊端

不能对数组的原始值进行改变,只能修改提取出来之后的数据.

二位数组

在Java中无真正的多维数组,只是数组的数组

定义

 int [ ] [ ] a=new int [行] [列];

或者

 int [ ] [ ] a;
 ​
 a=new int [行] [列];

例子

 package ch05;
 ​
 public class ch053 {
 ​
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         int [][]a=new int [3][4];
         for(int i=0;i<a.length;i++) {//此处可以使用a的属性length进行代表行数
             for(int j=0;j<a[i].length;j++) {
                 System.out.print(a[i][j]+" ");
             }
             System.out.println();
         }
     }
 }

使用foreach语句进行输出

 package ch05;
 ​
 public class ch053 {
 ​
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         int [][]a=new int [3][4];
         for(int[] row : a) {
             for(int col : row) {
                 System.out.println(col);
             }
         }
     }
 }

综合使用:打印杨辉三角

 package ch05;
 ​
 public class ch054 {
 ​
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         int n=10;
         int [][]a=new int [n][];
         for(int i=0;i<a.length;i++){
             a[i]=new int[i+1];
         }
         a[0][0]=1;
         for(int i=1;i<a.length;i++) {
             a[i][0]=1;
             a[i][a[i].length-1]=1;
             for(int j=1;j<a[i].length-1;j++)
             {
                 a[i][j]=a[i-1][j-1]+a[i-1][j];
             }
         }
         for(int [] row:a) {
             for(int col:row) {
                 System.out.print(col+" ");
             }
             System.out.println();
         }
     }
 ​
 }