#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    21
    Rep Power
    0

    Java noob. Help with Arrays.


    So I decided to start learning Java by using the book Objects First book using the IDE BlueJ but I'm stuck on what many could consider an incredibly simple question. So I have these 2 classes. I seem to be stuck on the easier things which I can't get my head around. Basically I'm stuck on what type to make the array and how to complete the method addTrack. Any help is greatly appreciated!

    Code:
    import java.util.ArrayList;
    
    /**
     * Class to represent a CD.
     * 
     * @author marc/murray
     * @version December 2004/2007/2012
     */
    
    public class CD 
    {
      private String artist;
      private String title;
      private int numTracks;
      // Declare array called tracks here
      private 
    
      public CD(String a, String t)
      {
        artist = a;
        title = t;
        // Initialise numTracks here the current number of tracks in the array tracks
        // Create the array teacks here - need to use some 'sensible' maximum size!
      }
    
      public String getArtist()
      {
        return artist;
      }
    
      public String getTitle()
      {
        return title;
      }
    
      public void addTrack(Track t)
      {
        // add track t to the array tracks + update the count of tracks
        
        
      }
    
    
      public String totalRunningTime() {                      
         // calculate total running time and return in mins:secs format as a String
         return "0:0"; // modify this
      }
    
      
      public String longestTrack() {                      
         // return the title of the longest track
         return "nowt so far"; // modify this
      }
    
      // Challenge exercise
      public ArrayList<String> findTracks(String s) {
        // Return an ArrayList containing all the titles that containg String s
        return null; //modify this
      }
    }
    and

    Code:
    import java.util.ArrayList;
    /**
     * Class to test CD implementation
     * 
     * @author marc/murray
     * @version December 2004/2007
     */
    public class CDTester
    {
        public void test()
        {
        CD mycd = new CD("Van Morrison", "Astral Weeks");
        // add some tracks
        
        mycd.addTrack(new Track("Slim Slow Rider", 423));
        mycd.addTrack(new Track("Astral Weeks", 320));
        mycd.addTrack(new Track("Young Lovers Do", 276));
        mycd.addTrack(new Track("Ballerina", 365));
    
        // find out total
        System.out.println("Total running time is " + mycd.totalRunningTime());
        // Result should be Total running time is 23:04
    
        // find longest track
        System.out.println("Track with longest running time is " + mycd.longestTrack());
        // Result should be Track with longest running time is Slim Slow Rider
        
        CD myothercd = new CD("Teenange Fanclub", "Thirteen");
        myothercd.addTrack(new Track("Fear of Flying", 324));
        System.out.println("Total running time is " + myothercd.totalRunningTime());
        // Result should be Total running time is 5:24
        
        // find longest track
        System.out.println("Track with longest running time is " + myothercd.longestTrack());
        // Result should be Track with longest running time is Fear of Flying
     
        // challenge exercise - find tracks
        /* Remove these comments to test these if you have attempted it
            System.out.println("Track with 'er' are :");
            ArrayList <String> tracks = mycd.findTracks("er");
            for (String s : tracks) {
                System.out.println(s);
            }
        */
        /* Result should be:
        Track with 'er' are :
        Slim Slow Rider
        Young Lovers Do
        Ballerina
        */
       }
    }
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Hi,

    Originally Posted by TTG123
    Basically I'm stuck on what type to make the array
    what kind of elements will the tracks list hold? If you're not sure, just look at what kind of objects the addTrack() method takes.



    Originally Posted by TTG123
    and how to complete the method addTrack.
    I guess you know how to insert an element at a specific index? The first unused index is given by numTracks.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    21
    Rep Power
    0
    Originally Posted by Jacques1
    Hi,



    what kind of elements will the tracks list hold? If you're not sure, just look at what kind of objects the addTrack() method takes.





    I guess you know how to insert an element at a specific index? The first unused index is given by numTracks.
    Would it be "private String[] tracks;" ?
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Originally Posted by TTG123
    Would it be "private String[] tracks;" ?
    Only if the addTrack() takes a String argument. And that's not the case (at least in the code you posted).

    The track array is supposed to consist of Track objects, so its type is Track[].
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    21
    Rep Power
    0
    Sorry to be a bother but you could explain to me what it means I have to do in the comment "// Initialise numTracks here the current number of tracks in the array tracks". I made the array "tracks = new Track[5];"
  10. #6
  11. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Originally Posted by TTG123
    Sorry to be a bother but you could explain to me what it means I have to do in the comment "// Initialise numTracks here the current number of tracks in the array tracks".
    When you've freshly created a CD, and you haven't added any tracks yet, the number of tracks is obviously 0. Each time you add a track, this number must be incremented.



    Originally Posted by TTG123
    I made the array "tracks = new Track[5];"
    Um, why did you choose 5 as the maximum number of tracks? CDs usually have 10-15 tracks.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    21
    Rep Power
    0
    I managed to figure that out. How would I go around finding the total run time of the tracks? Currently I have a method written but it won't compile.

    Code:
        
    public String totalRunningTime() {                      
        // calculate total running time and return in mins:secs format as a String
        int total = 0;
    
    
        for (int i = 0; i < tracks.length; i++) 
        {
          total = total + tracks[i];
        }
        return total; // modify this
     }
  14. #8
  15. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Originally Posted by TTG123
    Currently I have a method written but it won't compile.
    Please read the error message and the comment:
    Code:
    // calculate total running time and return in mins:secs format as a String
    The result is supposed to be a String, which you can already tell by the return value. Your result is an integer (namely the number of seconds).
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    21
    Rep Power
    0
    Sorry I should clarify. I was just trying to get the method working before I tried to format the retuned value properly. What I'm trying to do is to find the total run time of the CD in seconds. And then display it in the form of minutes and seconds. e.g if it was 312 seconds it would display as 5:12.
  18. #10
  19. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Originally Posted by TTG123
    I was just trying to get the method working before I tried to format the retuned value properly.
    Well, but you still can't return an int when the method is defined to return a String. You'd need to do something like this:
    Code:
    System.out.println("total in seconds: " + total);
    return "";
    or cast the int into a String:
    Code:
    return "" + total;
    But in this case I'd simply write down the end result and not fumble with intermediate results.
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    21
    Rep Power
    0
    I'm getting there. So now I have this class:

    Code:
    public class CD 
    {
      private String artist;
      private String title;
      private int numTracks;
      // Declare array called tracks here
      private Track[] tracks;
    
      public CD(String a, String t)
      {
        artist = a;
        title = t;
        // Initialise numTracks here the current number of tracks in the array tracks
        numTracks = 0;
        tracks = new Track[8];
        // Create the array tracks here - need to use some 'sensible' maximum size!
      }
    
      public String getArtist()
      {
        return artist;
      }
    
      public String getTitle()
      {
        return title;
      }
    
      public void addTrack(Track t)
      {
        // add track t to the array tracks + update the count of tracks
        tracks[numTracks] = t;
        numTracks++;
      }
    
    
      public String totalRunningTime() 
      {                      
         int totalSecs = 0;
         for(int i = 0; i < numTracks; i++) {
             totalSecs = totalSecs + tracks[i].getRunningTime();
            }
         int minutes = totalSecs/60;
         int seconds = totalSecs%60;
     
         String result = minutes + ":" + seconds;
         return result;
      }
    
      
      public String longestTrack() {                      
         int longest = 0
    
         for (int i = 0; i < numTracks; i++ ) 
         {
           if ( ) 
           {
             
             
           }
         }
        
          
        
         return ;
      }
    How do I complete the longestTrack method similarly to the totalRunningTime method?
  22. #12
  23. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Originally Posted by TTG123
    How do I complete the longestTrack method similarly to the totalRunningTime method?
    Do you know pseudocode? Forget the Java program for a second and write down a general "algorithm" for determining the biggest object in a list:
    Code:
    def getBiggest(list):
    	biggest := list.first	// assume the first element is the biggest
    	each element in list:
    		if element.size > biggest.size:
    			biggest := element
    	return biggest
    When you know how the logic works, it shouldn't be too hard to implement it in Java.

    By the way, is there a reason why you're so parsimonious with the length of the tracks array? Just set it to 20 or 50 or 100. Don't worry about Java not being able to handle such "big" arrays. But as a teacher, I'd say that 8 is not exactly a "sensible maximum".
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    21
    Rep Power
    0
    I have the general structure of the method, I have it as

    Code:
      public String longestTrack() 
      {
          int longest = 0;
          for(int i = 0; i < numTracks; i++)
          {
              if ( )
              {
                  
              }
              
          }
          
         String result = longest.getTitle;
          
    
         // return the title of the longest track
        return result; // modify this
      }
    I just can't seem to get my head around what to put within the for loop and if statement.
  26. #14
  27. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Please, take some time to read the pseudocode and figure out how to implement this in Java. With "some time" a mean like half an hour, not 5 minutes.

    Also check your data types. If "longest" is an int, it cannot have a getTitle() method.
  28. #15
  29. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    21
    Rep Power
    0
    I got it! Thank you so much for your help tonight! You've kept me sane!

    Code:
      public String longestTrack() 
      {
        Track longest = tracks[0];
    
        for (int i = 0; i < numTracks; i++ ) 
        {
          if (tracks[i].getRunningTime() > longest.getRunningTime()) 
          {
            longest = tracks[i];
          }
        }
     
          return longest.getTitle();
      }

IMN logo majestic logo threadwatch logo seochat tools logo