Idiot's Note Three: 循环中Break和“<=xxx.length”的细节注意

首先查看代码:

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)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值