JAVA第六周上机练习

1.编写一个简单程序,要求数组长度为5,静态赋值10,20,30,40,50,在控制台输出该数组的值。

package one;

public class Test02 {

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.println(arr[i]);
}

}

}

2.编写一个简单程序,要求数组长度为5,动态赋值10,20,30,40,50,在控制台输出该数组的值。
package one;

public class Test02 {

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 < 5; i++) {
System.out.println(arr[i]);
}
}

}

3.编写一个简单程序,定义整型数组,里面的元素是{23,45,22,33,56},求数组元素的和、平均值
package one;

public class Test02 {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 23, 45, 22, 33, 56 };
double sum = 0;
double avg = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
avg = sum / arr.length;
System.out.println("和为" + sum);
System.out.println("平均值为" + avg);

}

}

4.在一个有8个整数(18,25,7,36,13,2,89,63)的数组中找出其中最大的数及其下标。
package one;

public class Test02 {

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 index = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
System.out.println("最大值是" + max);
System.out.println("最大值下标为" + index);

}

}

5. 将一个数组中的元素逆序存放(知识点:数组遍历、数组元素访问)
package one;

public class Test02 {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 1, 2, 3, 4, 5 };
int arr2[] = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
int value = arr[arr.length - (i + 1)];
arr2[i] = value;
System.out.println(arr2[i]);
}

}

}

6、有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。(附加题)
package one;

public class Test02 {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 1, 2, 4, 5 };
int[] arr2 = new int[5];
int a = 3;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > a) {
arr2[i] = a;
for (i = i + 1; i < arr2.length; i++) {
arr2[i] = arr[i - 1];
}
} else {
arr2[i] = arr[i];
}
}
for (int i = 0; i < 5; i++) {
System.out.println(arr2[i]);
}

}

}

posted @ 2020-04-09 11:51  董文博。  阅读(...)  评论(...编辑  收藏