首先查看代码:
public class BreakTesting {
public static void main(String[] args){
int[] arrayOfInts={32,54,13,69,75,30,11,5,89};
System.out.println("Type in the Num:");
Scanner sc=new Scanner(System.in);
int i=sc.nextInt();
boolean bl=false;
int j=0;
for(j=0;j<arrayOfInts.length;j++){
if(i==arrayOfInts[j]){
bl=true;
break;
}
}
if(bl){
System.out.println("Found "+i+" at index "+(j+1));
}else{
System.out.println(i+ " not found");
}
}
}
outprint:
Type in the Num:
5
Found 5 at index 8
含break的代码块:
for(j=0;j<arrayOfInts.length;j++){
if(i==arrayOfInts[j]){
bl=true;
break;
}
}
break的功能是从该语句所在的switch or 循环中跳出来,执行后续的语句。
注意:
arrayOfInts.length是从1开始的,而Index是从0开始的,arrayOfInts[j],如果int j=arrayOfInts.length就会抛出:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at Ttt.BreakTesting.main(BreakTesting.java:14)