java控制语句 if-else while do-while for return break continue goto switch default

时间:2022-12-13 05:30:38

if

for

//: object/ForEachFloat.java
package object;
import java.util.Random;
public class ForEachFloat
{
public static void main(String[] args)
{
Random rand = new Random();//47是随机种子,如果不提供种子,默认为系统时间
float f[] = new float[10];
for(int i = 0; i < 10; i++)
f[i] = rand.nextFloat(); //生成0-1之间的float值
System.out.println('\n');
for(float x : f) //将f数组的值按顺序赋予x
System.out.printf("%f\t",x);
}
}

break continue goto

java 没有goto,可以用标签 和 break;continue 配合完成goto 的功能

//: object/LabeledFor.java

package object;

import static net.mindview.util.Print.*;

public class LabeledFor{
public static void main(String[] args)
{
int i = 0;
outer: //Can't have statements here
for(;true;){//infinite loop 无限循环
inner: //Can't have statements here
for(;i<10;i++){
print("i = " + i);
if(i == 2){
print("continue");
continue;
}
if(i == 3){
print("break");
i++; //otherwise i never
// gets incremented
break;
}
if(i == 7){
print("continue outer ");
i++; //otherwise i never
// gets incremented
continue outer;//回到outer标记重新循环
}
if(i == 8){
print("break outer");
break outer; //跳出outer 标记的循环语句
}
for(int k = 0;k<5;k++){
if(k == 3){
printf("contniue inner ");
continue inner;
}
}
}
}
}
}