Java_题目_添加手机对象并返回要求的数据

一、需求:
定义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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值