我想不出该怎么做才好。因此,我有一个数组,可以包含6个项。我有一个.txt文件,它在一行中包含一首歌,然后在下一首歌的旁边,然后是下一首歌,然后是谁。对几个人来说如此等等。在我的.txt文件中总共有12行,但是我只能在数组中放置总共6项。所以我想知道,我如何把这首歌的标题和艺术家放在数组上的一个索引中。这样我就可以把它打印出来,作为“艺术家”的标题。
我的代码很短,所以查看它可能会有帮助。
/**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文件中的内容
Ode to Joy
Bach
The Sleeping Beauty
Tchaikovsky
Lullaby
Brahms
Canon
Bach
Symphony No. 5
Beethoven
The Blue Danube Waltz
Strauss最后的输出应该打印为:
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发布于 2014-03-10 00:49:42
你只需替换:
cd.add(title + artist);出自:
cd[i] = title + " by " + artist;把它打印出来:
System.out.println(cd[i]);发布于 2014-03-10 00:50:01
我会使用@dasblinkenlight的解决方案,但是我会在Track类中添加一个toString方法。
我还会更进一步,使它成为一个不可变的值类型对象,但这可能超出了您的需要。
toString将允许您执行以下操作:
System.out.println(“轨道:”+轨道);
https://stackoverflow.com/questions/22290248
复制相似问题