import java.util.Scanner; public class FunctionAverage { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入想要创建数组的内存:"); int x = sc.nextInt(); System.out.println("请输入想要计算的数组值:"); double[] a = new double[x]; for(int i =0;i<a.length;i++) { a[i]=sc.nextDouble(); } double avg = (double) FunctionAverage.avg(a); System.out.println("该数组的平均数为:"+avg); } public static double avg(double[] a) { double sum=0; double avg=0; for(int i=0;i<a.length;i++) { sum+=a[i]; } avg=sum/a.length; return avg; } }
运行结果如下:
import java.util.Scanner; public class ArrayText { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //定义该数组的内存 int[] x = new int[5]; for(int a=0;a<x.length;a++) { System.out.println("请输入第"+(a+1)+"个元素:"); x[a]=sc.nextInt(); } int max = x[0]; int min = x[0]; for(int b = 0;b<x.length;b++) { if(max<x[b]) { max=x[b]; }else if(min>x[b]){ min=x[b]; } } System.out.println("数组中的元素最大值为:"+max); System.out.println("数组中的元素最小值为:"+min); } }
程序运行结果如下:
import java.util.Scanner; public class ArrayText2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入数组的长度:"); int len = sc.nextInt(); int arr[] = new int[len]; System.out.println("请输入数组元素 : "); for(int i =0; i < arr.length ; i++){ arr[i] = sc.nextInt(); } resver(arr); printArray(arr); } public static void resver(int arr[]) { for(int start = 0 , end=arr.length-1;start <= end;start++,end--) { int temp = arr[start]; arr [start] = arr [end]; arr [end] = temp; } } public static void printArray(int[] arr) { System.out.print("["); for(int x = 0;x<arr.length;x++) { if(x == arr.length-1) { System.out.println(arr[x]+"]"); }else { System.out.print(arr[x]+","); } } } }
程序运行结果如下:
import java.util.Scanner; public class ArrayText4 { public static void main(String[] args) { Scanner sc= new Scanner(System.in); //定义一个数组内存 int[] arr= new int[5]; for(int x = 0;x<arr.length;x++) { System.out.println("请您输入第"+(x+1)+"数据"); arr[x] = sc.nextInt(); } System.out.println("请输入要查询的数据:"); int num = sc.nextInt(); int target = getIndex2(arr,num); if(target>0) { System.out.println("该元素在数组中的索引值为:"+target); }else { System.out.println("查询不到索引值"); } } public static int getIndex2(int arr[],int target) { for(int a= 0;a<arr.length;a++) { if(target==arr[a]) { return a; } } return -1; } }
程序运行结果如下: