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