题目要求
按要求实现:
(1)封装一个新闻类,包含标题和内容属性,提供get、set方法,重写只打印方法
(2)只提供一个带参数的构造器,实例化对象时,只初始化标题;并且新闻一:新冠确诊病例超千万,数百万印度教信徒赴恒河“圣浴”引民新闻二:男子突然想起2个月前钓的鱼还在网兜里,捞起一看赶紧放生(3)将新闻对象添加到ArrayList集合中,并且进行倒序遍历;
(4)在遍历集合过程中,对新闻标题进行处理,超过15字的只保留前1(5)在控制台打印遍历出经过处理的新闻标题;
代码
package collectionHomework;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class Homework01 {
public static void main(String[] args) {
News news = new News("新闻一");
news.setContents("新冠确诊病例超千万,数百万印度教信徒赴恒河“圣浴”引民众担忧");
News new2 = new News("新闻二");
new2.setContents("男子突然想起2个月前钓的鱼还在网兜里,捞起一看赶紧放生");
List list = new ArrayList();
list.add(news);
list.add(new2);
//反转数组内容
Collections.reverse(list);
///遍历数组
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
News next = (News) iterator.next();
System.out.println(next.getTitle() + ":" + next.getContents());
}
iterator = list.iterator();
//对新闻标题进行处理,超过15字的只保留前15个字
while (iterator.hasNext()) {
News next = (News) iterator.next();
String str = "";
if (next.getContents().length() > 15){
System.out.println( next.getTitle() + ": " + next.getContents().substring(0,15));
}
else System.out.println(next.getTitle() + ":" + next.getContents());
}
}
}
class News {
private String title;
private String contents;//内容
public void showtitle() {
System.out.println(this.title);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public News(String title) {
this.title = title;
}
}