java - 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;
}
}
解决方案
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!");
}
推荐阅读
- python - 一个条形图中的多个条形图
- android - 在使用 MVVM Android 的 Switch 组件上使用自定义属性进行双向数据绑定
- python - 为什么 Tkinter 为我的按钮创建一个新窗口?
- python - 没有找到与 lal 匹配的分布
- c# - 如何在c#中从没有SPLIT的字符串中获取单词
- java - Mac上有_JAVA_OPTIONS吗?
- python - fromkeys 方法的意外结果
- swift - SwiftUI - 数组中只有一个对象属性为真
- c++ - Qt Quick2 为单例类类型创建 qmlRegisterSingletonType
- python - 使用 pandas 对行进行子集化