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