循环语句

Java中有以下几种循环结构:

  • while
  • do...while
  • for
  • foreach

while

示例代码

int i = 0;
while(i < 10) {
  i++;
  System.out.println(i);
}

do..while

示例代码

int i = 0;
do {
  i++;
  System.out.println(i);
} while (i < 10);

for

示例代码

for (int i = 0; i < 10; i++) {
  System.out.println(i);
}

foreach

示例代码

int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers){
  System.out.println(x);
}
String [] names = {"James", "Larry", "Tom", "Lacy"};
for(String name : names) {
  System.out.println(name);
}

break与continue

示例代码

String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
  if( name == "Tom" ) {
    break;
  }
  System.out.println(name); // James Larry
}
for( String name : names ) {
  if( name == "Tom" ) {
    continue;
  }
  System.out.println(name); // James Larry Lacy
}

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress