1.制作汽车类,现有格式汽车5款,名字,生产日期 与 价格。
将他们存放在集合中并按价格排序 .
要求: 输出结果(使用三种方式: for循环 iterator迭代子 foreach循环)
package com.demo03;
import java.util.*;
public class Car {
private String name;
private String brand;
private float price;
private Date date;
public Car() {
}
public Car(String name,String brand,float price,Date date) {
this.name=name;
this.brand=brand;
this.price=price;
this.date=date;
}
public String toString() {
return this.name+",\t"+this.brand+",\t"+this.price+",\t"+this.date;
}
}
package com.demo03;
import java.util.*;
public class CarPrint {
public static void main(String[] args) {
List<Car> carList = new ArrayList<Car>();
Date a = new Date(1503254365563l);
Date b = new Date(1474465735633l);
Date c = new Date(1449525264365l);
Date d = new Date(1444365324232l);
Date e = new Date(1494322135554l);
carList.add(new Car("car1","大众",130000,a));
carList.add(new Car("car2","奥迪",454800,b));
carList.add(new Car("car3","奇瑞",88800,c));
carList.add(new Car("car4","特斯拉",439200,d));
carList.add(new Car("car5","奔驰",842800,e));
System.out.println("for循环方法输出:");
System.out.println("名称 品牌 价格 生产时间");
for(int i=0;i<carList.size();i++){
System.out.println(carList.get(i));
}
System.out.println("——————————————————————————————————");
System.out.println("iterator迭代子方法输出:");
System.out.println("名称 品牌 价格 生产时间");
Iterator<Car> iter = carList.iterator();
while (iter.hasNext()){
Car m = iter.next();
System.out.println(m);
}
System.out.println("——————————————————————————————————");
System.out.println("foreach循环方法输出:");
System.out.println("名称 品牌 价格 生产时间");
for(Car s : carList){
System.out.println(s);
}
}
}
2、2.已知有十六支男子足球队参加世界杯。写一个程序,把这16 支球队随机分为4 个组。
List lst = new ArrayList();
for (int i=1;i<=16;i++){
lst.add(“球队”+i);
}
Random rand = new Random();
package com.demo03;
import java.util.*;
public class Team {
public static void main(String[] args) {
ArrayList<String> team = new ArrayList<String>();
for (int i=1;i<=16;i++){
team.add("球队"+i);
}
Random rand = new Random();
for(int i=1;i<5;i++) {
System.out.println("第"+i+"组球队分组名单为:");
for(int n=1;n<5;n++) {
int j = rand.nextInt(team.size());
String s = team.get(j);
System.out.print(s+" ");
team.remove(s);
}
System.out.println("\n");
}
}
}
本文介绍了如何使用Java编程创建汽车类,包含车型、生产日期和价格属性,并将汽车实例存储在集合中进行价格排序。通过for循环、iterator迭代子和foreach循环三种方式展示排序结果。此外,还展示了如何随机将16支足球队分为4个组,利用ArrayList存储球队信息并结合Random类进行随机分组操作。

2924

被折叠的 条评论
为什么被折叠?



