Java代码题 创建一个碟包,需要能保存CD和DVD碟片,记录碟片的发行信息,有存入、取出、外借、归还、点数、遍历等功能。
时间: 2024-01-01 22:06:37 浏览: 21
public class DiscPackage {
private List<Disc> discs;
public DiscPackage() {
discs = new ArrayList<>();
}
public void addDisc(Disc disc) {
discs.add(disc);
}
public Disc getDisc(String title) {
for (Disc disc : discs) {
if (disc.getTitle().equals(title)) {
return disc;
}
}
return null;
}
public void removeDisc(String title) {
for (int i = 0; i < discs.size(); i++) {
if (discs.get(i).getTitle().equals(title)) {
discs.remove(i);
break;
}
}
}
public void lendDisc(String title) {
Disc disc = getDisc(title);
if (disc != null && !disc.isLent()) {
disc.setLent(true);
}
}
public void returnDisc(String title) {
Disc disc = getDisc(title);
if (disc != null && disc.isLent()) {
disc.setLent(false);
}
}
public int getTotalPoints() {
int totalPoints = 0;
for (Disc disc : discs) {
totalPoints += disc.getPoints();
}
return totalPoints;
}
public void printDiscs() {
for (Disc disc : discs) {
System.out.println(disc);
}
}
}
public abstract class Disc {
private String title;
private String artist;
private int releaseYear;
private boolean lent;
private int points;
public Disc(String title, String artist, int releaseYear, int points) {
this.title = title;
this.artist = artist;
this.releaseYear = releaseYear;
this.points = points;
this.lent = false;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public int getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(int releaseYear) {
this.releaseYear = releaseYear;
}
public boolean isLent() {
return lent;
}
public void setLent(boolean lent) {
this.lent = lent;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
@Override
public String toString() {
return "Title: " + title + ", Artist: " + artist + ", Release Year: " + releaseYear + ", Lent: " + lent + ", Points: " + points;
}
}
public class CD extends Disc {
private int numTracks;
public CD(String title, String artist, int releaseYear, int points, int numTracks) {
super(title, artist, releaseYear, points);
this.numTracks = numTracks;
}
public int getNumTracks() {
return numTracks;
}
public void setNumTracks(int numTracks) {
this.numTracks = numTracks;
}
@Override
public String toString() {
return "CD - " + super.toString() + ", Number of Tracks: " + numTracks;
}
}
public class DVD extends Disc {
private int duration;
public DVD(String title, String artist, int releaseYear, int points, int duration) {
super(title, artist, releaseYear, points);
this.duration = duration;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
@Override
public String toString() {
return "DVD - " + super.toString() + ", Duration: " + duration;
}
}