【问题标题】:Need to split a string using a delimiter and store its values in a Constructor (Java)需要使用分隔符拆分字符串并将其值存储在构造函数(Java)中
【发布时间】:2020-09-22 17:53:56
【问题描述】:

Song(String info):通过解析包含标题、艺术家和时间的字符串来初始化歌曲,分号和空格用作分隔符。例如,U2 的歌曲《Where the Streets Have No Name》的 info String 是

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() {
        
    }
}

【问题讨论】:

  • 那么问题到底是什么?
  • 在 public Song(String info) 构造函数中,我不知道如何将歌曲长度存储到 int[] time ArrayList 中,所以我希望你们中的一个可以帮助我。对于该构造函数,我们正在解析一个如下所示的字符串:(java "Where the Streets Have No Name; U2; 5:36"),我们需要分离每个值并将它们存储在类的变量中。
  • 我会将持续时间更改为总秒数,并将其存储起来。它可以快速轻松地从秒转换为您需要的任何形式。

标签: java split constructor


【解决方案1】:

您应该使用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]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2010-12-26
    • 2017-05-19
    • 2015-10-21
    • 1970-01-01
    • 2012-12-01
    • 2016-03-03
    相关资源
    最近更新 更多