The first (for-each,数组)
来源:互联网 发布:软件开发年终工作总结 编辑:程序博客网 时间:2024/05/22 10:28
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方法。
- The first (for-each,数组)
- The First (for-each ,Array)
- jquery $().each、$.each、for 遍历数组
- For the first time!
- The first article for testing ...
- the first wblog for seraphiw
- just for the first time
- POJ1007 for the first time
- the first try for clang
- Show the implicit parameter for each instance.
- JDK5.0 二维数组for each循环
- JAVA for-each循环与数组
- For-each循环访问多维数组
- 使用each方法代替for遍历数组
- 自用基础5-数组+for each
- ubuntu taste for the first time
- Life in America for the first week
- plan for the first term of junior
- UIGestureRecognizer学习笔记
- 二叉树题目集锦1
- iOS应用国际化教程(2014版)
- 有什么方法把word转换成pdf
- 【水题】Codeforces Round #289 509E Pretty Song
- The first (for-each,数组)
- 用juery 实现的select特效 jquery.easydropdown.min.js
- Android MMS定制
- 机器学习之正则化
- Android官方入门文档[16]创建一个Fragment代码片段
- 程序用调试用的宏
- UITableView常用
- [算法系列之三十一]最近公共祖先(LCA)
- 从零开始编写自己的JavaScript框架(一)