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