歌曲(字符串信息(:通过解析一个字符串来初始化歌曲,该字符串包含标题、艺术家和时间,并使用分号和空格作为分隔符。例如,歌曲的信息字符串";街道无名之地;U2是
java "Where the Streets Have No Name; U2; 5:36"
时间以小时、分钟和秒为单位,用冒号分隔。分钟和秒是介于0和59之间的数字。如果歌曲少于一小时,则只给出分和秒。同样,如果歌曲少于一分钟,则只给出秒数。
这是我到目前为止的代码:
import java.util.Arrays;
public class Song {
private String title;
private String artist;
private int[] time;
private static final String INFO_DELIMITER = "; ";
private static final String TIME_DELIMITER = ":";
private static final int IDX_TITLE = 0;
private static final int IDX_ARTIST = 1;
private static final int TIME = 2;
public Song(String title, String artist, int[] time) {
this.title = title;
this.artist = artist;
this.time = Arrays.copyOf(time, time.length);
}
public Song(String info) {
String words[] = info.split(INFO_DELIMITER);
this.title = words[0];
this.artist = words[1];
String temp = words[2];
this.time = Arrays.copyOf(Integer.parseInt(words[2], Integer.parseInt(words[2].length)));
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
public int[] getTime() {
return Arrays.copyOf(time, time.length);
}
public String toString() {
}
}
应该使用TIME_DELIMITER
拆分包含时间的单词。
如果可以使用Java 8 Stream API,time
可以设置如下:
this.time = Arrays.stream(temp.split(TIME_DELIMITER))
.mapToInt(Integer::parseInt)
.toArray();
或使用旧式编码:
String[] strTime = word[2].split(TIME_DELIMITER);
time = new int[strTime.length];
for (int i = 0; i < strTime.length; i++) {
time[i] = Integer.parseInt(strTime[i]);
}