java - 需要使用分隔符拆分字符串并将其值存储在构造函数(Java)中
问题描述
Song(String info):通过解析包含标题、艺术家和时间的字符串来初始化一首歌曲,其中分号和空格用作分隔符。例如,U2 的歌曲“Where the Streets Have No Name”的信息字符串是
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]);
}
推荐阅读
- mysql - 有没有办法判断 MySQL 联合查询中的结果集何时发生变化?
- ios - 将标签放在 UIView 的中间三分之一处
- google-cloud-platform - 如何联系 Google 支持以获取 MarketPlace 支持
- ios - FCM 通知在 iOS Cordova 应用程序中突然停止工作
- c - 打印列表并用逗号分隔值并以点结尾
- c - 数据结构化的 C 语言中的两个编程问题
- swagger - Swagger Hub `Try it out` 返回 TypeError: Failed to fetch for localhost when using browser option
- notifications - Moodle 限制提交 通知指定老师
- python - 在python中检查列表中的字符串时减少for循环的使用
- ios - 重新加载表格视图后如何处理键盘?