一、需求:
定义Javabean类:Phone
Phone属性:品牌,价格。
main方法中定义一个集合,存入三个手机对象。
分别为:小米,1000。苹果,8000。锤子,2999。
定义一个方法,将价格低于3000的手机信息返回。
二、代码:
public class Phone {
//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 PhoneTest {
public static void main(String[] args) {
//1.创建集合对象
ArrayList<Phone> list = new ArrayList<>();
//2.创建手机的对象
Phone p1 = new Phone("小米", 1000);
Phone p2 = new Phone("苹果", 8000);
Phone p3 = new Phone("锤子", 2999);
//3.添加数据
list.add(p1);
list.add(p2);
list.add(p3);
//4.调用无返回值方法
getPhoneInfo(list);
//小米,1000
//锤子,2999
//5.调用返回值方法
ArrayList<Phone> phoneInfoList = getPhone(list);
for (int i = 0; i < phoneInfoList.size(); i++) {
Phone phone = phoneInfoList.get(i);
System.out.println(phone.getBrand() + ":" + phone.getPrice());
}
//小米:1000
//锤子:2999
}
//1)无返回值方法
public static void getPhoneInfo(ArrayList<Phone> list) {
for (int i = 0; i < list.size(); i++) {
Phone p = list.get(i);
int price = p.getPrice();
if (price < 3000) {
System.out.println(p.getBrand() + "," + p.getPrice());
}
}
}
//2)如果需要返回多个数据,将数据放到一个容器中,再返回容器
//集合 数组
public static ArrayList<Phone> getPhone(ArrayList<Phone> list) {
//定义一个集合,存储价格低于3000的手机对象
ArrayList<Phone> resultList = new ArrayList<>();
//遍历集合
for (int i = 0; i < list.size(); i++) {
Phone p = list.get(i);
int price = p.getPrice();
//如果当前手机价格低于3000,将手机对象添加到resultList中
if (price < 3000) {
resultList.add(p);
}
}
//返回resultList
return resultList;
}
}