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