public static void main1(String[] args) {
int[] arr = new int[8];
// 经典for循环, 用于给数组赋值或其他和下标相关的操作
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 20);
}
// 增强for遍历数组, 只读
for (int tmp : arr) {
System.out.print(tmp + " ");
}
System.out.println();
//0 1 2 3 4 5 6 7
//10 8 0 1 19 3 17 6
//数组中最重要的算法 : 取子数组
//取所有奇数, 目标 :
//0 1 2 3
//1 19 3 17
//需要两个新数组,因为奇数的个数未知,这里取极端情况:原数组中全是奇数。
//创建临时数组存储所有奇数
int[] tempArr = new int[arr.length];
//设置计数器,为第二个新数组的长度
int count=0;
for(int i=0;i<arr.length;i++){
if(arr[i]%2!=0) {
tempArr[count++]=arr[i];
}
}
//对数组进行缩容
int[] arr2 = new int[count];
for(int i=0;i<arr2.length;i++){
arr2[i]=tempArr[i];
}
for(int temp:arr2){
System.out.print(temp+" ");
}
System.out.println();
}
public static void main(String[] args) {
Student[] stuArr = new Student[10];
String[] name1 = {"李", "王", "张", "杨", "陈", "刘", "赵","钱","孙","周","吴","郑","司马","诸葛"};
String[] name2 = {"伟", "丽", "芳", "刚", "良", "琳", "鑫", "军", "磊", "飞", "娜","晓明","芷若","亮","懿"};
for (int i = 0; i < stuArr.length; i++) {
int id = i + 1;
int index1 = (int) (Math.random() * 10000) % name1.length;
int index2 = (int) (Math.random() * 10000) % name2.length;
String name = name1[index1] + name2[index2];
int grade = (int) (Math.random() * 6 + 1);
double score = (int) (Math.random() * 101);
stuArr[i] = new Student(id, name, grade, score);
}
// 遍历
for(Student stu:stuArr){
System.out.println(stu.say());
}
System.out.println("---------------------------------------");
//创建一个临时的数组,假设全为五年级同学
Student[] tempArr = new Student[stuArr.length];
//计数器:用来充当临时数组的索引,以及计算数组的长度
int count=0;
for (int i=0;i<stuArr.length;i++) {
//三年级的学生对象赋值到临时数组中
if(stuArr[i].getGrade()==3) {
tempArr[count++] = stuArr[i];
}
}
//对临时数组进行缩容
Student[] stuArrSon = new Student[count];
for(int i=0;i<stuArrSon.length;i++){
stuArrSon[i]=tempArr[i];
}
for(Student student:stuArrSon){
System.out.println(student.say());
}
}
【Java基础[数组及对象数组取子数组]】
于 2022-07-19 16:20:37 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)