break:
package BreakDemo;
public class BreakDemo {
public static void main(String[] args) {
String[] a = {"cat", "dog", "laser horse", "ketchup", "horse", "horbse"};
for (int i = 0; i < a.length; i += 1) {
for (int j = 0; j < 3; j += 1) {
System.out.println(a[i]);
if (a[i].contains("horse")) {
break;//执行一次后跳出了当前的循环
}
}
}
}
}
结果:包含horse内容的元素执行了一次break后跳出,不继续执行后两次的循环。这表明break是跳出了当前循环体的循环,提前结束了循环工作。
continue:
package ContinueDemo;
public class ContinueDemo {
public static void main(String[] args) {
String[] a = {"cat", "dog", "laser horse", "ketchup", "horse", "horbse"};
for (int i = 0; i < a.length; i += 1) {
if (a[i].contains("horse")) {
continue;
}//包含horse的项直接跳过循环后续的语句,重新返回起始的if判断重新判断。
for (int j = 0; j < 3; j += 1) {
System.out.println(a[i]);
}
}
}
}
结果:
continue语句的作用是跳过本次循环体中余下尚未执行的语句,立即进行下一次的循环条件判定,可以理解为仅结束本次循环。
注意:continue语句并没有使整个循环终止。
一些运用:
Write a function windowPosSum(int[] a, int n) that replaces each element a[i] with the sum of a[i] through a[i + n], but only if a[i] is positive valued. If there are not enough values because we reach the end of the array, we sum only as many values as we have.
这是cs61B里的一个exercise
这里给出我的代码:
package exercise4;
public class exercise4 {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
windowPosSum(a, 2);
System.out.println(java.util.Arrays.toString(a));
}
/* public static int windowPosSum(int[ ]a,int n){
int sum=0;
int i=0;
if(a.length<n){
for(i=0;i<=a.length;i++){
if()
sum=sum+a[i];
}
a[i]=sum;
}
else{
for(i=0;i<=n;i++){
sum=sum+a[i];
}
a[i]=sum;
}
return a[i];
}
*/ //这里一开始我没看到条件1:positive valued因此只冗杂的分析了代码边界的问题。于是注释掉了。
public static void windowPosSum(int[] a, int n) {
for (int i = 0; i < a.length; i++) {
if (a[i] <= 0) {//判断数组里的每一个值是否都是positive valued
continue;//如果是不满足的数就跳出不执行
}
for (int j = 0; j < n; j++) {
if (i + j + 1 > a.length - 1) {
break;//如果列表里没有足够的数可以加入替换列表里,就跳出该层循环。
}
a[i] = a[i] + a[i + j + 1];//i=0时,j=0,1,2,...n-1故i+j+1=i+n(同理i=2....等)
}
}
}
}
结果:
java.util.Arrays.toString()用来将数组转换成String类型输出,入参可以是long,float,double,int,boolean,byte,object 型的数组,使用此方法可以很方便地输出数组,而不用一个一个地输出数组元素。