Set the Package to rockcountdown Set the Name to Song Unchec

Set the Package to rockcountdown.

Set the Name to Song.

Uncheck \"public static void main...\".

Add the rank, title, and artist fields to the Song.

Add getters and setters to the properties to make them properties (note that a property is a field plus a getter and/or setter). Productivity tip: Right-click in the source code editor | Source... | Generate getters and setters...

Add a constructor to initialize the fields. Tip: Right-click in the source code editor | Source... | Generate Constructor using Fields...

Ensure that Song objects can be created an initialized:

Create a new package under the src folder called sbccunittest.

Download (right-click Save Link As...) SongListTester.java into sbccunittest. Right-click on your project, then choose Refresh to show the new file as in your project.

SongListTester is a JUnit test class.

Its job is to test various aspects of your program.

The JUnit view will tell you which tests passed and failed.

SongListTester will output your program\'s score in the console view.

Run | Run As | JUnit Test.

If you\'ve coded Song up correctly, the testNewSongFromFields() test will pass, and the JUnit view in Eclipse will show a green bar. The console will show your score. If there are any problems, fix them so that the unit test passes.

Allow a new Song object to be created from a tab delimited string.

Open SongListTester in the editor.

Notice that two of the tests in SongListTester are commented out.

Select the lines that define testNewSongFromTabDelimitedString, then type Ctrl-/. This will uncomment that test. It should also result in a syntax error, since testNewSongFromTabDelimitedString uses a Song constructor that takes just one String. You will fix the compilation error next.

Add the one-string constructor to Song:

The idea of the one-string constructor is that the caller passes in a tab delimited string containing the Song properties. Here is an example of the string:

\"21    Born to Run    Bruce Springsteen\"

The constructor splits the String up into tokens and sets the fields equal to the corresponding token.

Right-click in the editor | Source | Generate constructor from superclass...

OK.

Note that this creates a constructor for you that takes no parameters. It includes an initial call to super().

Add a String parameter. Save. This should clear the compilation error.

Use String.split() on \"\\t\" to split the parameter up into tokens. If you are not sure how to split a string in Java, remember that Google is your friend.

Assign each token to the corresponding field. Hints: You should trim leading and trailing whitespace before assigning the token to the field. This prevents any tabs or newlines from becoming part of a song property. Also: you\'ll need to convert a string to an integer for the rank field. If you are not sure how to do this, try googling \"java convert string to integer example\".

When you think you\'ve got the constructor working properly, try running SongListTester again. If testNewSongFromTabDelimitedString doesn\'t pass, modify your new constructor to fix any problems.

In the next step, we\'ll create the Main class shown in the UML diagram above. It will have a method called main(), that is the starting point for our application.  main()\'s job is to:

Get the song list filename from the standard input.

Read the whole file into a string in memory.

For each line in the string in memory, create a Song object from the line, and add the Song object to a list of songs.

Print the list out, starting at the end of the list and working towards the beginning.

Main class:

Use the New Class wizard to create a new class.

Set the Package to rockcountdown.

Set the Name to Main.

Check \"public static void main...\".

Add code to main() to do the following:

Scan the song list filename from the standard input (don\'t print a prompt to the user). Use the Scanner object\'s nextLine() method to get the filename.

Read the whole file into a String with readFileToString().

Split the String on \"\ \ \" to get an array of lines from the file. \"\ \ \" is the end-of-line marker in Windows files. See wikipedia if you want a thorough coverage of end-of-line markers on various operating systems.

Create a new ArrayList<Song>.

For each line in the array (of lines from the file), create a song object and add it to the ArrayList.

Create a StringBuilder that will hold the text we want to output.

Iterate through the array list from the end to the start, appending: the song\'s rank, \"\\t\", the song\'s title, and \"\ \ \".

Write the StringBuilder to the standard output (out). This will result in a blank line after the last song is printed.

Write \"Complete\" to the standard output.

Test your program manually:

Download (right-click | Save Link As...) this song list file.  You can use it to test your program.

In the package explorer, right-click on your Main class | Run As | Java Application. In the Console view, type the name of the song list file (rs30.txt), then type <ENTER>.

Your program should output the countdown (see the Sample Input and Output section below).

Unit Test:

Uncomment testReverseList(). This may cause some errors because the uncommented code makes calls to libaries that haven\'t been imported yet. You can type Ctrl-Shift-o to \"organize the imports\". This should fix the problems.

Run SongListTester as a JUnit Test.

If there are any problems, modify your code to address them and get testReverseList() to pass.

Main +main songs ArrayList Song rank int title String artist String int, String, parameter) +Song(String)

Solution

Main.java

package rockcountdown;

import static java.lang.System.*;

import java.io.*;
import java.util.*;

import org.apache.commons.io.*;

public class Main {

   public static void main(String[] args) throws IOException {
       Scanner scanner = new Scanner(in);
       String fileName = scanner.nextLine();

       File file = new File(fileName);


       String fileContents = FileUtils.readFileToString(file);
       String[] fileLines = fileContents.split(\"\ \ \");

       ArrayList<Song> songArrayList = new ArrayList<>();

       for (String line : fileLines) {
           songArrayList.add(new Song(line));
       }

       StringBuilder builder = new StringBuilder();

       for (Song song : songArrayList) {
           builder.insert(0, song.getRank() + \"\\t\" + song.getTitle() + \"\ \");
       }

       out.println(builder.toString());
       out.println(\"Complete\");
   }

}


Song.java

package rockcountdown;

public class Song {

   // These are \"properties\" because they have getters and setters. Individually they are \"fields.\"
   private int rank;


   public Song(int rank, String title, String artist) {
       super();
       this.rank = rank;
       this.title = title;
       this.artist = artist;
   }


   public Song(String s) {
       super();

       String[] params = s.split(\"\\t\");
       rank = Integer.valueOf(params[0].trim());
       title = params[1].trim();
       artist = params[2].trim();
   }


   private String title;

   private String artist;


   public int getRank() {
       return rank;
   }


   public void setRank(int rank) {
       this.rank = rank;
   }


   public String getTitle() {
       return title;
   }


   public void setTitle(String title) {
       this.title = title;
   }


   public String getArtist() {
       return artist;
   }


   public void setArtist(String artist) {
       this.artist = artist;
   }
}


SongListTester.java

package sbccunittest;


import static org.junit.Assert.*;

import java.io.*;
import java.util.*;

import org.apache.commons.io.*;
import org.junit.*;

import rockcountdown.*;

public class SongListTester {

   public static int totalScore = 0;

   public static int extraCredit = 0;

   public static InputStream defaultSystemIn;

   public static PrintStream defaultSystemOut;

   public static PrintStream defaultSystemErr;

   public static String newLine = \"\ \ \"; // System.getProperty(\"line.separator\");


   @BeforeClass
   public static void beforeTesting() {
       totalScore = 0;
       extraCredit = 0;
   }


   @AfterClass
   public static void afterTesting() {
       System.out.println(\"Estimated score (w/o late penalties, etc.) = \" + totalScore);
   }


   @Before
   public void setUp() throws Exception {
       defaultSystemIn = System.in;
       defaultSystemOut = System.out;
       defaultSystemErr = System.err;
   }


   @After
   public void tearDown() throws Exception {
       System.setIn(defaultSystemIn);
       System.setOut(defaultSystemOut);
       System.setErr(defaultSystemErr);
   }


   @Test
   public void testNewSongFromFields() throws Exception {
       Song song = new Song(1, \"Some Title\", \"Some Artist\");
       assertEquals(1, song.getRank());
       assertEquals(\"Some Artist\", song.getArtist());
       song.setTitle(\"Some other title\");
       assertEquals(\"Some other title\", song.getTitle());
       totalScore += 5;
   }


   @Test
   public void testNewSongFromTabDelimitedString() throws Exception {
       Song song = new Song(\"12\\tA Change Is Gonna Come\\tSam Cooke\");
       assertEquals(12, song.getRank());
       assertEquals(\"A Change Is Gonna Come\", song.getTitle());
       assertEquals(\"Sam Cooke\", song.getArtist());
       totalScore += 5;
   }


   @Test
   public void testReverseList() throws Exception {
       ArrayList<String> songList = new ArrayList<String>();
       Collections.addAll(songList, songArray);

       ArrayList<String> reverseTitleList = new ArrayList<String>();
       Collections.addAll(reverseTitleList, reverseTitleArray);

       int randomNdxToDelete = (int) (Math.random() * songList.size());
       songList.remove(randomNdxToDelete);
       reverseTitleList.remove(reverseTitleList.size() - randomNdxToDelete - 1);

       StringBuilder sb = new StringBuilder();
       for (String song : songList)
           sb.append(song).append(newLine);
       try {
           FileUtils.writeStringToFile(new File(\"rs_top_30_songs.txt\"), sb.toString());
       } catch (IOException e) {
           e.printStackTrace();
       }
       sendToStdinOfTestee(\"rs_top_30_songs.txt\ \");
       final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
       System.setOut(new PrintStream(myOut));

       Main.main(null);
       String output = myOut.toString();
       System.setOut(defaultSystemOut);

       sb = new StringBuilder();
       for (String song : reverseTitleList)
           sb.append(song).append(newLine);

       sb.append(newLine + \"Complete\" + newLine);
       String expectedOutput = sb.toString();

       // Convert to common end-of-line system.
       output = output.replace(\"\ \ \", \"\ \");
       expectedOutput = expectedOutput.replace(\"\ \ \", \"\ \");

       assertEquals(expectedOutput, output);
       totalScore += 10;
   }


   public void sendToStdinOfTestee(String message) {
       System.setIn(new ByteArrayInputStream(message.getBytes()));
   }


   private final String[] songArray = { \"1   Like a Rolling Stone   Bob Dylan\", \"2   Satisfaction   The Rolling Stones\",
           \"3   Imagine   John Lennon\", \"4   What\'s Going On   Marvin Gaye\", \"5   Respect   Aretha Franklin\",
           \"6   Good Vibrations   The Beach Boys\", \"7   Johnny B Goode   Chuck Berry\", \"8   Hey Jude   The Beatles\",
           \"9   Smells Like Teen Spirit   Nirvana\", \"10   What\'d I Say   Ray Charles\", \"11   My Generation   The Who\",
           \"12   A Change Is Gonna Come   Sam Cooke\", \"13   Yesterday   The Beatles\", \"14   Blowin\' in the Wind   Bob Dylan\",
           \"15   London Calling   The Clash\", \"16   I Want to Hold Your Hand   The Beatles\",
           \"17   Purple Haze   Jimi Hendrix\", \"18   Maybellene   Chuck Berry\", \"19   Hound Dog   Elvis Presley\",
           \"20   Let It Be   The Beatles\", \"21   Born to Run   Bruce Springsteen\", \"22   Be My Baby   The Ronettes\",
           \"23   In My Life   The Beatles\", \"24   People Get Ready   The Impressions\",
           \"25   God Only Knows   The Beach Boys\", \"26   (Sittin on) the Dock of the Bay   Otis Redding\",
           \"27   Layla   Derek and the Dominos\", \"28   A Day in the Life   The Beatles\", \"29   Help!   The Beatles\",
           \"30   I Walk the Line   Johnny Cash\" };

   private final String[] reverseTitleArray = { \"30   I Walk the Line\", \"29   Help!\", \"28   A Day in the Life\",
           \"27   Layla\", \"26   (Sittin on) the Dock of the Bay\", \"25   God Only Knows\", \"24   People Get Ready\",
           \"23   In My Life\", \"22   Be My Baby\", \"21   Born to Run\", \"20   Let It Be\", \"19   Hound Dog\", \"18   Maybellene\",
           \"17   Purple Haze\", \"16   I Want to Hold Your Hand\", \"15   London Calling\", \"14   Blowin\' in the Wind\",
           \"13   Yesterday\", \"12   A Change Is Gonna Come\", \"11   My Generation\", \"10   What\'d I Say\",
           \"9   Smells Like Teen Spirit\", \"8   Hey Jude\", \"7   Johnny B Goode\", \"6   Good Vibrations\", \"5   Respect\",
           \"4   What\'s Going On\", \"3   Imagine\", \"2   Satisfaction\", \"1   Like a Rolling Stone\" };

}

Set the Package to rockcountdown. Set the Name to Song. Uncheck \
Set the Package to rockcountdown. Set the Name to Song. Uncheck \
Set the Package to rockcountdown. Set the Name to Song. Uncheck \
Set the Package to rockcountdown. Set the Name to Song. Uncheck \
Set the Package to rockcountdown. Set the Name to Song. Uncheck \
Set the Package to rockcountdown. Set the Name to Song. Uncheck \
Set the Package to rockcountdown. Set the Name to Song. Uncheck \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site