package com.wys.java; //数组做为方法参数 //定义方法,打印输出数组元素的值 public class arrayFunctionDemo { public void printArray(int[] arr){ for(int i=0; i<arr.length; i++){ System.out.print(arr[i]+" "); } System.out.println(); } public static void main(String[] args) { int[] arr = {10,20,30,40,50}; arrayFunctionDemo admo = new arrayFunctionDemo(); admo.printArray(arr); } }
查找数组中是否有某个值:
package com.wys.java; import java.util.Scanner; public class arraySearch { //查找数组中是否有某个值 public boolean arrSearch(int[] arr, int n){ boolean flag = false; for(int i=0; i<arr.length; i++){ if(arr[i] == n){ flag = true; //找到了 break; } } return flag; } public static void main(String[] args) { int[] arr1 = {10,20,30,40,50,60}; System.out.println("请输入要查找的元素:"); Scanner sc = new Scanner(System.in); int target = sc.nextInt(); //保存输入的目标值 arraySearch arrsearch = new arraySearch(); boolean flag = arrsearch.arrSearch(arr1, target); if(flag){ System.out.println("数组中有该元素"); }else{ System.out.println("数组中没有该元素"); } } }
结果: