我在弄清楚如何正确执行此操作时遇到了麻烦。所以我有这个数组,可以包含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
您可以替换为:
cd.add(title + artist);
通过:
cd[i] = title + " by " + artist;
并使用以下命令打印:
System.out.println(cd[i]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句