【Java作业】Week06

来源:互联网 发布:如何分析竞价数据 编辑:程序博客网 时间:2024/06/05 12:43

作业一

package org.westos_13;import java.util.ArrayList;import java.util.Iterator;/** * 1:集合的嵌套遍历  需求:  我们班有学生,每一个学生是不是一个对象。所以我们可以使用一个集合表示我们班级的学生。ArrayList<Student>  但是呢,我们旁边是不是还有班级,每个班级是不是也是一个ArrayList<Student>。 而我现在有多个ArrayList<Student>。也要用集合存储,怎么办呢? * @author asus-pc * */public class TestDemo {public static void main(String[] args) {ArrayList<ArrayList<Student>> grade = new ArrayList<ArrayList<Student>>();//定义集合表示班级,装载学生ArrayList<Student> class1 = new ArrayList<Student>();ArrayList<Student> class2 = new ArrayList<Student>();ArrayList<Student> class3 = new ArrayList<Student>();ArrayList<Student> class4 = new ArrayList<Student>();//grade.add(class1);grade.add(class2);grade.add(class3);grade.add(class4);//定义学生变量Student stu1 = new Student(18,"一班学生");Student stu2 = new Student(222,"一班学生");Student stu3 = new Student(555,"二班学生");Student stu4 = new Student(200,"三班学生");Student stu5 = new Student(123,"四班学生");//向班级中添加学生class1.add(stu1);class1.add(stu2);class2.add(stu3);class3.add(stu4);class4.add(stu5);//遍历并输出学生信息————————使用size()和get()//for(int i = 0;i < a.size();i ++) {//for(int j = 0;j < a.get(i).size();j++) {//ArrayList<Student> temp = a.get(i);//System.out.println(temp.get(j));//}//}//使用迭代器Iterator<ArrayList<Student>> it1 = grade.iterator();while(it1.hasNext()) {Iterator<Student> it2 = it1.next().iterator();while(it2.hasNext()) {System.out.println(it2.next());}}}}class Student {int age;String name;public Student(int age, String name) {this.age = age;this.name = name;}public Student() {}@Overridepublic String toString() {return "Student [age=" + age + ", name=" + name + "]";}}


作业二

package org.westos_13;/** * 获取10个1-20之间的随机数,要求不能重复 * @author asus-pc * */public class TestDemo1 {public static void main(String[] args) {int ran[] = new int[20];for(int i = 0;i < 20;i ++) {ran[i]= (int)Math.random() * 20 + 1;for(int j = 1;j < i;j++) {if(ran[i] == ran[j]) {i--;}}}}}


作业三
package org.westos_13;import java.util.ArrayList;import java.util.Iterator;/** * 使用ArrayList集合存储自定义对象并遍历(三种方式去实现) * @author asus-pc * */public class TestDemo2 {public static void main(String[] args) {ArrayList class1 = new ArrayList();//创建自定义对象Student stu1 = new Student(18,"一班学生");Student stu2 = new Student(222,"一班学生");Student stu3 = new Student(555,"二班学生");Student stu4 = new Student(200,"三班学生");Student stu5 = new Student(123,"四班学生");//往集合中添加自定义对象class1.add(stu1);class1.add(stu2);class1.add(stu3);class1.add(stu4);class1.add(stu5);//遍历并输出//方法一       调用toArray方法Object stu[] = class1.toArray();for(int i = 0;i < stu.length;i ++) {Student temp = (Student)stu[i];System.out.println(temp);}//方法二 _______使用size和getSystem.out.println("--------------------");for(int i =0;i < class1.size();i ++) {System.out.println(class1.get(i));}//方法三————————使用迭代器System.out.println("------------");Iterator it = class1.iterator();while(it.hasNext()) {System.out.println(it.next());}}}