首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按适当顺序将项添加到数组中

按适当顺序将项添加到数组中
EN

Stack Overflow用户
提问于 2014-03-10 00:38:47
回答 2查看 1.5K关注 0票数 1

我想不出该怎么做才好。因此,我有一个数组,可以包含6个项。我有一个.txt文件,它在一行中包含一首歌,然后在下一首歌的旁边,然后是下一首歌,然后是谁。对几个人来说如此等等。在我的.txt文件中总共有12行,但是我只能在数组中放置总共6项。所以我想知道,我如何把这首歌的标题和艺术家放在数组上的一个索引中。这样我就可以把它打印出来,作为“艺术家”的标题。

我的代码很短,所以查看它可能会有帮助。

代码语言:javascript
复制
/**This program creates a list of songs for a CD by reading from a file*/
import java.io.*;

public class CompactDisc
{
    public static void main(String [] args) throws IOException
    {
    FileReader file = new FileReader("Classics.txt");
    BufferedReader input = new BufferedReader(file);
    String title;
    String artist;

    //Declare an array of songs, called cd, of size 6
    String[] cd = new String[6];

    for (int i = 0; i < cd.length; i++)
    {
        title = input.readLine();
        artist = input.readLine();  
        // fill the array by creating a new song with 
        // the title and artist and storing it in the 
        // appropriate position in the array
     cd.add(title + artist);
    }

    System.out.println("Contents of Classics:");
    for (int i = 0; i < cd.length; i++)
    {
        //print the contents of the array to the console
    }
  }
}

这就是.txt文件中的内容

代码语言:javascript
复制
Ode to Joy
Bach
The Sleeping Beauty
Tchaikovsky
Lullaby
Brahms
Canon
Bach
Symphony No. 5
Beethoven
The Blue Danube Waltz
Strauss

最后的输出应该打印为:

代码语言:javascript
复制
Contents of Classics
Ode to Joy by Bach
The Sleeping Beauty by Tchaikovsky
Lullaby by Brahms
Canon by Bach
Symphony No. 5 by Beethoven
The Blue Danube Waltz by Strauss
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-10 00:49:42

你只需替换:

代码语言:javascript
复制
cd.add(title + artist);

出自:

代码语言:javascript
复制
cd[i] = title + " by " + artist;

把它打印出来:

代码语言:javascript
复制
System.out.println(cd[i]);
票数 2
EN

Stack Overflow用户

发布于 2014-03-10 00:50:01

我会使用@dasblinkenlight的解决方案,但是我会在Track类中添加一个toString方法。

我还会更进一步,使它成为一个不可变的值类型对象,但这可能超出了您的需要。

toString将允许您执行以下操作:

System.out.println(“轨道:”+轨道);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22290248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档