增强 for 循环
- 数组中重点使用
- Java5引入了一种主要用于数组或集合的增强型for循环
- Java增强for循环语法格式:
for(声明语句:表达式){
//代码}
- 声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
- 表达式:表达式是要访问的数组名,或者是返回值为数组的方法。
public class A0119 {
public static void main(String[] args) {
int[]num={
3,6,9,12,15};//定义了一个数组
System.out.println(num);
System.out.println(num[0]);
System.out.println(num[1]);
System.out.println("===============");
for (int a = 0; a < 5; a++) {
System.out.print(num[a]+"\t");
}
System.out.println();
//遍历数组的元素
for (int b :num){
System.out.print(b+"\t");
run:
[I@1b6d3586
3
6
===============
3 6 9 12 15
3 6 9 12 15
break continue
- break在任何循环语句的主题部分,均可用break控制循环的流程,break用于强行退出循环,不执行循环中剩余的语句。(break语句也在switch语句中使用)
- continue语句用于在循环语句体重,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。
例:
int a = 0;
while (a < 16) {
a++;
if (a % 3 == 0) {
break;}
System.out.print(a+"\t");
}
System.out.println("\n===========");
int b = 0;
while (b < 16)
{
b++;
if (b % 3 == 0) {
continue;} //continue之后的while语句是被跳过的
System.out.print(b+"\t");}
run:
1 2
===========
1 2 4 5 7 8 10 11 13 14 16
goto关键字
- goto关键字很早就在程序设计语言中出现。尽管goto仍是Java的一个保留字,但并未在语言中得到正式使用;Java没有goto。然而,在break和continue这两个关键字的身上,我们仍然能看出一些goto的影子—带标签的break和continue。
- "标签"是指后面跟一个冒号的标识符,例如:label:
- 对Java来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望在其中嵌套另一个循环,由于break和continue关键字通常只中断当前循环,但若随同标签使用,它们就会中断到存在标签的地方。
输出1-100的质数,每输出5个换一行:
public static void main(String[] args) {
//输出1-100的质数 每5个输出一行
int c=0;
comehere:for (int a = 3; a <= 100; a++)//comehere: 这个是标签符(字符串+:)
{
for(int b=2;b<a/2;b++)
{
if (a%b==0)continue comehere;}//continue 跳到标签处
c=c+1;
System.out.print(a+"\t" + "");
if (c%5==0){
System.out.println();
run:
3 4 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97