I'm having trouble figuring out how to properly do this. So I have this array that can contain 6 items. I have this .txt file that contains a song on a line, and then on the next who the song is by, and then the next song, and then who that's by. So on and so forth for a few. In total there are 12 lines in my .txt file, but I can only put a total of 6 items in my array. So I'm wondering, how can I put both the title of the song + the artist into a single index on the array. Such that I can print it out later as the Title "by" Artist.
My code is decently short, so maybe viewing it might help.
/**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
}
}
}
This is what's in the .txt file
Ode to Joy
Bach
The Sleeping Beauty
Tchaikovsky
Lullaby
Brahms
Canon
Bach
Symphony No. 5
Beethoven
The Blue Danube Waltz
Strauss
The final output is supposed to print as:
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
String result = title + "||" + artist;) with a character or string you choose, place it into the array. And to split the string in the display loop, useString#split. Of course, this doesn't take into account any errors that could come from malformed files and such.