The First (for-each ,Array)
来源:互联网 发布:linux 关闭图形界面 编辑:程序博客网 时间:2024/05/22 07:01
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 ,Array)
- The first (for-each,数组)
- 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
- Find the first covering prefix of array
- Show the implicit parameter for each instance.
- ubuntu taste for the first time
- Life in America for the first week
- plan for the first term of junior
- see C++ for the first(初识C++)
- The First Study Day For JavaWeb
- It's time for the first article
- for each
- for each
- 博客第一天
- json常用工具
- iOS零基础
- Partition List
- Tomcat JK(NOT JK2) Apache2 带SSL/vHost 整合
- The First (for-each ,Array)
- Leetcode -- Set Matrix Zeroes
- 国家工商总局与淘宝握手言和 将共同治理假货
- CSS之多列布局
- 面试题中常见的String类问题
- extjs5 sencha cmd 5 的介绍及使用
- Java内部类
- Hibernate之抓取策略
- 74138集成电路译码器