首页 > 解决方案 > Java中的for循环有问题

问题描述

我正在使用 for 循环检查数组中是否存在给定值,问题是它直接在 else 分支上跳转并打印要检查的值(即使不满足条件)。通过删除休息; 它只遍历 if 语句一次并打印 if 语句 println() 和 else 语句 println() 的 6 次。为什么会这样?

public static void main(String[] args){
   checkArray(new int[]{1, 2, 3, 4, 5, 6, 7}, 4);
}

public static void checkArray(int[] q, int a){

   for(int i = 0; i < q.length; i++){
       if(a == q[i]){
           System.out.println("Number " + a + " is indeed present!");
       } else {
           System.out.println("Number " + a + " is not present!");
       }
       break;
    }

}

标签: java

解决方案


return在打印找到的消息后添加。并将未找到的消息移动到循环之后 - 您只想在检查整个数组之后打印它。

public static void checkArray(int[] q, int a)
{
   for (int i = 0; i < q.length; i++){
       if (a == q[i]) {
           System.out.println("Number " + a + " is indeed present!");
           return;  // Immediately exit the function
       }
    }
    // It will only get here if a is not in the array.
    System.out.println("Number " + a + " is not present!");
}

推荐阅读