需求:定义javabean 类:Phone
Phone 属性:品牌,价格。
main方法中定义一个集合,存入三个手机对象。
分别为:小米,1999。苹果,2999。华为,3000。
定义一个方法,将价格低于2000的手机信息返回。
public class Phone {
private String brand;
private int price;
public Phone(){
}
public Phone(String brand, int price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
import java.util.ArrayList;
public class main {
public static void main(String[] args) {
ArrayList<Phone> list = new ArrayList<>();
Phone p1 = new Phone("小米",1999);
Phone p2 = new Phone("苹果",2999);
Phone p3 = new Phone("华为",3000);
list.add(p1);
list.add(p2);
list.add(p3);
ArrayList<Phone> phoneImfolist = getPhoneImfo(list);
for (int i = 0; i < phoneImfolist.size(); i++) {
Phone phone =phoneImfolist.get(i);
System.out.println(phone.getBrand()+","+phone.getPrice());
}
}
public static ArrayList<Phone> getPhoneImfo(ArrayList<Phone> list){
ArrayList<Phone> resultlist = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Phone p = list.get(i);
int price = p.getPrice();
if(price<2000){
resultlist.add(p);
}
}
return resultlist;
}
}