/*1.编写一个简单程序,要求数组长度为5,静态赋值10,20,30,40,50,在控制台输出该数组的值。 */ package study; import java.util.*; public class homework { public static void main(String[] args) { int a[]= {10,20,30,40,50}; for (int i = 0; i < 5; i++) { System.out.println(a[i]); } } } /*2.编写一个简单程序,要求数组长度为5,动态赋值10,20,30,40,50,在控制台输出该数组的值。 */ package study; import java.util.*; public class homework { public static void main(String[] args) { int[] a=new int[5]; a[0]=10; a[1]=20; a[2]=30; a[3]=40; a[4]=50; for (int i = 0; i < 5; i++) { System.out.println(a[i]); } } } /*3.编写一个简单程序,定义整型数组,里面的元素是{23,45,22,33,56},求数组元素的和、平均值 */ package study; import java.util.*; public class homework { public static void main(String[] args) { int[] a={23,45,22,33,56}; int s=0; double p=0; for (int i = 0; i < 5; i++) { s+=a[i]; } p=s/5.0; System.out.println("数组元素的和是"+s+","+"平均值是"+p); } } /*4.在一个有8个整数(18,25,7,36,13,2,89,63)的数组中找出其中最大的数及其下标。 */ package study; import java.util.*; public class homework { public static void main(String[] args) { int[] a={18,25,7,36,13,2,89,63}; int max1=0,max2=0; for (int i = 0; i < 8; i++) { max1=a[i]>max1?a[i]:max1; for (int j = i+1; j < 8; j++) { max2=a[i]>a[j]?a[i]:a[j]; max1=max1>max2?max1:max2; } } System.out.println("最大的数是"+max1); for (int i = 0; i < 8; i++) { if(max1==a[i]) { System.out.println("最大的数的下标是"+i); } } } } /*5. 将一个数组中的元素逆序存放(知识点:数组遍历、数组元素访问) */ package study; import java.util.*; public class homework { public static void main(String[] args) { int[] a={18,25,7,36,13,2,89,63}; int[] b=new int[8]; for (int i = 0; i < 8; i++) { b[7-i]=a[i]; } for (int i = 0; i < 8; i++) { a[i]=b[i]; } for (int i = 0; i < 8; i++) { System.out.print(a[i]+","); } } }
/*6、有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。(附加题) */ package study; import java.util.*; public class homework { public static void main(String[] args) { System.out.print("请输入一个数(数组从小到大排列):"); Scanner input=new Scanner(System.in); int n=input.nextInt(); int s=0; int[] a={n,1,2,3,4,5,7}; for (int i = 0; i < a.length-1; i++) { s=a[i]; for (int j = i+1; j < a.length; j++) { a[i]=a[i]<a[j]?a[i]:a[j]; if(a[i]==a[j]) { a[j]=s; } } } for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }