基础输出数组
package cc.openhome;
import java.util.Arrays;
public class Score {
public static void main(String[] args) {
int[] scores={88,81,74,68,78,76,77,85,95,93};
System.out.println("第一次输出");
for(int i=0;i<scores.length;i++)
{
System.out.print(scores[i]);
System.out.print(" ");
}
通过索引改变值
scores[4]=0;
System.out.printf("%n第二次输出%n");
for(int i=0;i<scores.length;i++)
{
System.out.print(scores[i]);
System.out.print(" ");
}
增强版for循环;
会取得scores数组的第一个元素,指定给Score变量后执行循环体,接着取得Scores中的第二个元素,指定给score变量后执行循环体
System.out.printf("%n第三次输出%n");
for(int score:scores){
System.out.printf("%d ",score);
}
声明二位数组并赋值
System.out.printf("%n第四次输出%n");
int[][] cords={
{1,2,3},{4,5,6}
};
for(int x=0;x<cords.length;x++)
{ for(int y=0;y<cords.length;y++)
{
System.out.printf("%2d",cords[x][y]);
}
System.out.println(); }
增强式for语法
for(int[]row:cords){
for(int value:row)
{
System.out.printf("%2d",value);
}
System.out.println();}
row参考的是一维数组对象,外层for循环就是循环取得cords参考对象的每一个索引,将参考到的对象指定给int[]类型的row名称。
//使用60填充scores数组
Arrays.fill(scores,60);
for(int score2:scores)
{System.out.printf("%2d ",score2);}
System.out.println();
不规则二维数组
int [][] arr=new int[2][];
arr[0]=new int[]{1,2,3,4,5};
arr[1]=new int[]{1,2,3};
for(int[] row:arr)
{ for(int value:row)
{
System.out.printf("%2d",value);
}
System.out.println();
}
类类型建立数组
Integer[] score3=new Integer[3];
for(Integer score1:score3)
{System.out.printf("%d ",score1);}
System.out.println();
score3[0]=new Integer(99);
score3[1]=new Integer(90);
score3[2]=new Integer(86);
for(Integer score1:score3)
{System.out.printf("%d ",score1);}
}
}