1.For each 循坏,
只能遍历,不能修改;不能选择性循坏,用法:
for(int m: marks) {
System.out.println(m);
}
marks是一个整形数组的数组名,m为定义的变量,用来遍历marks中所有元素。
for each 循坏可以用来遍历多维数组,
2.二维数组的循坏,制表:
public class StudentScores {
public static void main(String[] args) {
int STUDENTS = 5;
int SUBJECTS = 3;
int[][] marks = new int[STUDENTS][SUBJECTS];
for (int i = 0; i < STUDENTS; i++) {
for (int j = 0; j < SUBJECTS; j++) {
marks[i][j] = (int) (Math.random() * 100);
}
}
System.out.print("Student\t");
for(int i=0;i<SUBJECTS;i++){
System.out.print("\tsubject"+(i+1));
}
System.out.println();
for(int i=0;i<STUDENTS;i++){
System.out.print("student"+(i+1)+"\t");
for(int j=0;j<SUBJECTS;j++){
System.out.print(marks[i][j]+"\t\t");
}
System.out.println();
}
}
}
结果是:
Studentsubject1subject2subject3
student1 15 81 37
student2 49 37 41
student3 87 18 75
student4 85 87 49
student5 77 56 79
用for each循坏为:
public class Scores_foreach {
public static void main(String[] args) {
int STUDENTS = 5;
int SUBJECTS = 3;
int[][] marks = new int[STUDENTS][SUBJECTS];
for (int i = 0; i < STUDENTS; i++) {
for (int j = 0; j < SUBJECTS; j++) {
marks[i][j] = (int) (Math.random() * 100);
}
}
System.out.print("Student\t");
for (int i = 0; i < SUBJECTS; i++) {
System.out.print("\tsubject" + (i + 1));
}
System.out.println();
int i = 0;
for (int[] student : marks) {
System.out.print("student" + ++i);
for (int value : student) {
System.out.print("\t"+value+"\t");
}
System.out.println();
}
}
}
结果一样。其中的代码段:
int i = 0;
for (int[] student : marks) {
System.out.print("student" + ++i);
for (int value : student) {
System.out.print("\t"+value+"\t");
}
System.out.println();
}
第二行:可以理解成:遍历二维数组marks的每一行,将marks拆成几个名为student的一维数组来循坏,第一步先打印student1,然后再遍历student中的每一个元素,加上制表符打印,换行后再遍历下一个student。
3.变量用驼峰表示,首字母小写。
4.to String 方法是object类的方法,Arrays.toString()方法是接受一个类型为数组的参数,并将其中的内容编程字符串;定义的数组是引用类型,有clone方法。