java如何在数组中查找指定元素

126次阅读
没有评论

共计 410 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,可以使用循环遍历数组来查找指定的元素。以下是一个简单的示例:

public class Main {public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5};
        int target = 3;
        
        boolean found = false;
        for (int i = 0; i < arr.length; i++) {if (arr[i] == target) {found = true;
                break;
            }
        }
        
        if (found) {System.out.println("Element " + target + " found in the array.");
        } else {System.out.println("Element " + target + " not found in the array.");
        }
    }
}

这段代码会在数组 arr 中查找元素 target,如果找到则输出找到的信息,如果没有找到则输出未找到的信息。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-11发表,共计410字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)