目前java主要有for循环、while循环、switch循环、forEach循环,本次主要讲一下for循环和forEach循环。
break、continue都可以跳出多层嵌套循环
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
break;
}
System.out.println("i = " + i + ", j = " + j);
}
}
输出结果:
i = 0, j = 0
i = 1, j = 0
i = 2, j = 0
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) {
continue;
}
System.out.println("i = " + i + ", j = " + j);
}
}
输出结果:
i = 0, j = 0
i = 0, j = 2
i = 1, j = 0
i = 1, j = 2
i = 2, j = 0
i = 2, j = 2
ok:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j == 5) {
break ok;
}
System.out.println("i = " + i + ", j = " + j);
}
}
输出结果:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 0, j = 3
i = 0, j = 4
int arr[][] = {{1,2,3,4},{5,6,7,8,9},{10,11}};
boolean found = false;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 5) {
found = true;
continue;
}
System.out.println("i = " + i + ", j = " + j);
}
}
输出结果:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 0, j = 3
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 1, j = 4
i = 2, j = 0
i = 2, j = 1
break;
int arr[][] = {{1,2,3,4},{5,6,7,8,9},{10,11}};
boolean found = false;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 5) {
found = true;
break;
}
System.out.println("i = " + i + ", j = " + j);
}
}
输出结果:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 0, j = 3
i = 2, j = 0
i = 2, j = 1
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.println("i = " + i + ", j = " + j);
if (j == 5) {
throw new Exception("跳出多层循环");
}
}
}
输出结果:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 0, j = 3
i = 0, j = 4
i = 0, j = 5
Exception in thread "main" java.lang.Exception: 跳出多层循环
at com.java.basic.HelloWord.main(HelloWord.java:55)
int arr[] = {1,2,3,4,5,6,7,8};
for (int a:arr) {
System.out.println("a = " + a);
if (a == 5) {
break;
}
}
输出结果:
a = 1
a = 2
a = 3
a = 4
a = 5
//java8,forEach循环
List<Student> list = new ArrayList<>();
Student jack = new Student();
jack.setName("jack");
jack.setAge(18);
jack.setGender("男");
list.add(jack);
Student jane = new Student();
jane.setName("Jane");
jane.setGender("女");
jane.setAge(19);
list.add(jane);
Student lihua = new Student();
lihua.setName("LiHua");
lihua.setGender("男");
lihua.setAge(20);
list.add(lihua);
list.forEach(student -> {
if ("女".equals(student.getGender())) {
return;
}
System.out.println("姓名:" + student.getName() + ", 性别:" + student.getGender() + ", 年龄:" + student.getAge());
});
输出结果:
姓名:jack, 性别:男, 年龄:18
姓名:LiHua, 性别:男, 年龄:20
关于面试:这一部分属于基础知识部分,一定要特别熟练,面试官可能不经常问,感觉默认面试者是全部熟练掌握了,如果不熟练,一定要多练习,多看看!!!