song.java /** This class represents a song */ public class Song { /** The title
ID: 3542936 • Letter: S
Question
song.java
/** This class represents a song */
public class Song
{
/** The title of the song */
private String title;
/** The artist who sings the song */
private String artist;
/** constructor
@param title The title of the song
@param artist The artist who sings the 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 + " ";
}
}
CompactDisc.java
/** This program creates a list of songs for a CD by
reading from a file
*/
import java.io.*;
import java.util.Scanner;
/** This program creates a list of songs for a CD by
reading from a file
*/
public class CompactDisc
{
public static void main(String [] args) throws IOException
{
File file = new File("Classics.txt");
Scanner input = new Scanner(file);
String title;
String artist;
//Declare an array of songs named cd, of size 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
}
System.out.println("Contents of Classics:");
for (int i = 0; i < cd.length; i++)
{
//print the contents of the array to the console
}
}
}
Classic.txt
Ode to Joy
Bach
The Sleeping Beauty
Tchaikovsky
Lullaby
Brahms
Canon
Bach
Symphony No. 5
Beethoven
The Blue Danube Waltz
Strauss
Explanation / Answer
public class CompactDisc
{
public static void main(String [] args) throws IOException
{
File file = new File("Classics.txt");
Scanner input = new Scanner(file);
String title;
String artist;
Song cd[6];
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.println(cd[i].toString() + " ");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.