life--

Java【封装一个新闻类,包含标题和内容属性】

题目:

1、封装一个新闻类,包含标题和内容属性,提供get、set方法,重写toString方法,打印对象时只打印标题;(10分)

2、只提供一个带参数的构造器,实例化对象时,只初始化标题;并且实例化两个对象:

  新闻一:中国多地遭雾霾笼罩空气质量再成热议话题

  新闻二:春节临近北京“卖房热”

3、将新闻对象添加到ArrayList集合中,并且使用ListIterator倒序遍历;

4、在遍历集合过程中,对新闻标题进行处理,超过15字的只保留前14个,然后在后边加“…”

5、在控制台打印遍历出经过处理的新闻标题;

大体思路:

1.创建News对象,并实例化两个新闻

2.将对象存入ArrayList中,调用其listIterator(iterator的子类),此时可以调用listIterator的Previous方法将指针向上值

3.通过向下转型调用News的length属性,判断长度是否超过15,输出对应数据

代码:

复制代码
//两个属性
  private String title;
    private String content;

    public News() {
    }

    public News(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
  //重写toString方法
    @Override
    public String toString() {
        return title;
    }
     
      //通过构造器创建两个对象
     News n1 = new News("新闻一:中国多地遭雾霾笼罩空气质量再成热议话题");
        News n2 = new News("新闻二:春节临近北京“卖房热”");
      //使用ArrayList存放数据
        ArrayList arr = new ArrayList();
        arr.add(n1);
        arr.add(n2);
     //使用迭代器
        ListIterator listIterator=arr.listIterator();
     //将迭代器位置移动到最后一位
        while (listIterator.hasNext()){
            listIterator.next();
        }
     //判断迭代器前面一位是否有数据,有数据就进入循环判断长度和确定输出数据并打印
        while (listIterator.hasPrevious()) {
            Object obj=listIterator.previous();
            News news=(News)obj;
            String title=news.getTitle();
            if(title.length()>15){
                System.out.println(title.substring(0, 15) + "...");
            }else {
                System.out.println(title);
            }
        }
复制代码

 

posted on   life--  阅读(343)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示