首页 > 解决方案 > 需要使用分隔符拆分字符串并将其值存储在构造函数(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() {
        
    }
}

标签: javasplitconstructor

解决方案


您应该使用 分割包含时间的单词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]);
}

推荐阅读