Please help with this codding assignment. I\'m using java netbeans. I can\'t fig
ID: 3856411 • Letter: P
Question
Please help with this codding assignment. I'm using java netbeans. I can't figure out how to print the contents of an array. Please leave comments explaining what you did, thank you, and on how to do input.
DOMAIN
/*This program represents a song*/
public class Song
{
private String title; //The title of the song
private String artist; //The artist who sings the song
/**
* constructor
*
* @param title The title of the song
* @param artist The artist who sings the song
*/
public Song()
{
}
public Song(String title, String artist)
{
this.title = title;
this.artist = artist;
}
/**
* toString method returns a description of the song
*
* @return a String containing the name of the song and the artist
*/
public String toString()
{
return title + " by " + artist;
}
}
DRIVER
/*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;
Song cd[] = new Song[6];
//Declare an array of songs, called cd, of size 6
for (int i = 0; i < cd.length; i++)
{
System.out.println("Enter title: " + i);
title = input.readLine();
System.out.println("Enter artist: " + i);
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
}
System.out.println("Contents of Classics:");
for (int i = 0; i < cd.length; i++)
{
//print the contents of the array to the console
System.out.println(cd.toString());
}
}
}
Explanation / Answer
Add classic.txt file as per your requirement.
CompactDisc.java
---------------------------
import java.io.*;
// program builds list of songs from a file
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;
final int NUM_SONGS = 6;
Song [] cd = new Song [NUM_SONGS];
for (int i = 0; i < cd.length; i++)
{
title = input.readLine();
artist = input.readLine();
cd[i] = new Song(title, artist);
}
System.out.println("Contents of Classics:");
for (int i = 0; i < cd.length; i++)
{
System.out.print(cd[i].toString());
}
}
}
--------------------------------------------------------------
Song.java
---------------------------
public class Song
{
private String title;
private String artist;
public Song(String title, String artist)
{
this.title = title;
this.artist = artist;
}
public String toString()
{
return title + " by " + artist + " ";
}
}