Results 1 to 10 of 10
  1. #1
    Join Date
    Mar 2009
    Posts
    38
    Rep Power
    0

    Default [SOLVED] Array trouble....

    Im trying to make a song organiser using 3 classes...
    1. The song object
    2. The organiser array
    3. The driver program...

    I have compiled the code without errors but i get runtime errors when trying to select "2" or "3" on the menu, please help...

    Here's my code, from the song class, array and driver

    Java Code:
    public class Song
    
    {
    
    	private String title;
    
    	private String artist;
    
    	private double length;
    
    	
    
    	//methods
    
    	//constructor
    
    	public Song(String inTitle, String inArtist, double inLength)
    
    	{
    
    		title = inTitle;
    
    		artist= inArtist;
    
    		length = inLength;
    
    			if (inLength <= 0)
    
    				{
    
    					inLength = 1.00;
    
    				}
    
    	}
    
    	
    
    	//getter methods
    
    	public String getTitle()
    
    		{
    
    			return title;
    
    		}
    
    	public String getArtist()
    
    		{
    
    			return artist;
    
    		}
    
    	public double getLength()
    
    		{
    
    			return length;
    
    		}
    
    	
    
    	//setter methods
    
    	public void setTitle(String newTitle)
    
    		{
    
    			title = newTitle;
    
    		}
    
    	public void setArtist(String newArtist)
    
    		{
    
    			artist = newArtist;
    
    		}
    
    	public void setLength(double newLength)
    
    		{
    
    			length = newLength;
    
    		}
    
    	//service methods
    
    	public String toString()
    
    	{
    
    		return getTitle() + " by " + getArtist() + " (" + getLength() + ")";
    
    	}
    
    }
    the array

    Java Code:
    public class SongOrganiser
    
    {
    
    	private final int SIZE = 10;
    
    	private Song[] songArr;// array of type String called Song. Used to store Song
    
    	private int count;  // int to keep count of the Song elements
    
    	
    
    	public SongOrganiser()
    
    	{
    
    		songArr = new Song[SIZE];
    
    		count = 0; 
    
    	}
    
    	public SongOrganiser (int size) 
    
    	{
    
    		if(size <= 0)
    
    			songArr = new Song[SIZE];
    
    		else 
    
    			songArr = new Song[size];
    
    			count = 0;
    
    	}
    
    	
    
    	//adding Song
    
    	public boolean add(Song newSong)
    
    	{
    
    		//check for space
    
    		if (count == songArr.length)
    
    			return false;
    
    		else
    
    		{
    
    			songArr[count] = newSong;
    
    			count++;
    
    			return true;
    
    		}
    
    	}
    
    	
    
    	//gets number of songs in array
    
    	public int getNoOffSongs()
    
    	{
    
    		return count; 
    
    	}
    
    	
    
    	
    
    	//finds song with title
    
    	public Song findSongWithTitle(String titleOfSong) //why do i get missing return statement error here???
    
    	{
    
    		for (int i = 0; i < count; i++)
    
    		{
    
    			if (titleOfSong.equalsIgnoreCase(songArr[i].getTitle()))
    
    				return songArr[i];
    
    		}
    
    		return null;
    
    				 
    
    	}
    
    	//get all songs
    
    	
    
    	public String getAllSongs()
    
    	{
    
    		
    
    		//String heading = "Number  Song Title     Artist         Length";
    
    		String details = "";
    
    		for (int i = 1; i <= count; i++)
    
    			details = i + "        " + songArr[i].getTitle() + "     "+ songArr[i].getArtist()+ "         "+songArr[i].getLength();
    
    			return  details;
    
    			
    
    	}
    
    	
    
    	//get songs by Artist
    
    	public String getSongsBy(String inArtist)
    
    	{
    
    		String artistDet = "";
    
    		for (int i = 1; i <= count;	i++)
    
    		{
    
    			if (inArtist.equalsIgnoreCase(songArr[i].getArtist()))
    
    			{
    
    				artistDet = songArr[i].toString();
    
    			}
    
    			return artistDet;	
    
    		}
    
    		return "not found";
    
    	}
    
    	//find the total length of all songs
    
    	public double findTotalLength()
    
    	{
    
    		double total = 0.0;
    
    		for(int i =1; i <= count; i++)
    
    		{
    
    			total += songArr[i].getLength();
    
    		}	
    
    		return total;
    
    	}
    
    	// display song with the longest playtime
    
    	public String longestSong()
    
    	{
    
    		String longSong = songArr[0].toString();
    
    		for (int i = 1; i <= count; i++)
    
    		{
    
    		if (songArr[i].getLength() > songArr[0].getLength())
    
    		longSong = songArr[i].toString();
    
    		}		
    
    		return longSong;
    
    	}
    
    	
    
    	//find songs with matching title
    
    	public String getAllSongsWith(String inTitle)
    
    	{
    
    		String TitleDet = "";
    
    		for(int i = 1; i <= count; i++)
    
    		{
    
    			if(songArr[i].getTitle().equalsIgnoreCase(inTitle))
    
    			TitleDet = songArr[i].toString();
    
    			
    
    		}	
    
    		return TitleDet;
    
    	}
    
    	//delete song
    
    	public boolean deleteSong(int index)
    
    	{
    
    		
    
    		for(int i = 1; i <= count; i++)
    
    		{
    
    			if(index <= count)
    
    			songArr[index] = null;//remove song here
    
    			return true;	
    
    		} 	
    
    		return false;
    
    	}
    
    	//sorting method here
    
    }
    the driver program
    Java Code:
    import java.util.Scanner;
    public class songOrganiserClient
    {
    	static SongOrganiser sO;
    	static Scanner key = new Scanner(System.in);
    	public static void main(String[] args)
    	{
    		sO = new SongOrganiser(10);
    		int choice = 0;
    		do
    		{
    			choice = Menu();
    			switch(choice)
    			{
    				case 0: 
    				System.out.println("Done...");
    					break;
    				case 1:
    				addSong();
    					break;
    				case 2:
    				displayAll();
    					break;
    				case 3:
    				totalAndAverage();
    				break;
    				
    			}	
    		}
    		
    		while(choice != 0);
    
    	
    	}
    	//methods here
    	//method for the menu
    	public static int Menu()
    	{
    	System.out.println("         My Song Organiser System         ");
    	System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    	System.out.println("1. Add a Song");
    	System.out.println("2. Display all songs");
    	System.out.println("3. Display total and average length of all songs");
    	System.out.println("4. Display song with longest length, i.e. playing time");
    	System.out.println("5. Display song by particular artist");
    	System.out.println("6. Display song containing substring");
    	System.out.println("7. Delete a song from organiser");
    	System.out.println("8. Change song details, given it's title");
    	System.out.println("9. Sort organiser by title and length");
    	System.out.println();
    	System.out.println();
    	System.out.println("0. exit");
    	System.out.println();
    	
    	System.out.print("Your choice?");
    	int choice = key.nextInt();
    	key.nextLine();
    	return choice;        	
    	}
    	//adding a song
    	public static void addSong()
    	{
    	System.out.println("Adding a new song");	
    	System.out.print("Song Title: ");
    	String title = key.nextLine();
    	System.out.print("Song Artist: ");
    	String artist = key.nextLine();
    	System.out.print("Song Length (in minutes, e.g. 4.36): ");
    	double length = key.nextDouble();
    	
    	Song s = new Song(title, artist, length);
    	if (sO.add(s) == true)
    		System.out.println("Success...");
    	else
    		System.out.println("No more space");
    	}
    	
    	// displaying all songs
    	public static void displayAll()
    	{
    		String songs = sO.getAllSongs();
    		if(songs.equals(""))
    			System.out.println("No song added yet");
    		else
    			System.out.println("Song(s) in the selection \n" + "Number  Song Title     Artist         Length \n" + songs);
    	}
    	
    	//displaying average and total number of playing time
    	public static void totalAndAverage()
    	{
    		double average = (sO.findTotalLength()/sO.getNoOffSongs());
    		System.out.println("Total length of all "+ sO.getNoOffSongs() + " song(s) is" + sO.findTotalLength());
    		System.out.println("Average length is "+ average);
    			
    	}
    	
    }

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,568
    Rep Power
    12

    Default

    Could you post the exact and entire runtime stack trace?

    This lets you see where in the code the problem is occurring - rather than what user action led to it. And also what the nature of the problem is: ArrayIndexOutOfBounds etc.

    Read the stack trace yourself. (Especially the first line which refers to a line in your code). But post it if you cannot understand it.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,568
    Rep Power
    12

    Default

    Hint:

    Java Code:
    public boolean add(Song newSong)
      {
        if (count == songArr.length)
          {
            return false;
          }
        else
          {
            songArr[count] = newSong;
            count++;
            return true;
          }
      }
    Java Code:
    songArr
    
    [song   song   song   song   ----   ----   ----]
      ^      ^      ^      ^      ^             ^
      |      |      |      |      |             |
      0      1      2      3    count     songArr.length-1

  4. #4
    Join Date
    Mar 2009
    Posts
    38
    Rep Power
    0

    Default

    Quote Originally Posted by pbrockway2 View Post
    Could you post the exact and entire runtime stack trace?

    This lets you see where in the code the problem is occurring - rather than what user action led to it. And also what the nature of the problem is: ArrayIndexOutOfBounds etc.

    Read the stack trace yourself. (Especially the first line which refers to a line in your code). But post it if you cannot understand it.
    Here's what i get when i try to display all songs (i.e. choosing "2" in the menu)

    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at SongOrganiser.getAllSongs(SongOrganiser.java:61)
    	at songOrganiserClient.displayAll(songOrganiserClient.java:81)
    	at songOrganiserClient.main(songOrganiserClient.java:22)
    and when i choose "3"
    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at SongOrganiser.findTotalLength(SongOrganiser.java:86)
    	at songOrganiserClient.totalAndAverage(songOrganiserClient.java:91)
    	at songOrganiserClient.main(songOrganiserClient.java:25)
    PS: This is after adding 2 songs to the Array.

    What is the problem there?? Unfortunately i only know how to read compile errors :(

  5. #5
    I-beck is offline Member
    Join Date
    Apr 2009
    Posts
    1
    Rep Power
    0

    Default

    eto ekonomicheski ne celesoobrazno

  6. #6
    Join Date
    Mar 2009
    Posts
    25
    Rep Power
    0

    Default

    Quote Originally Posted by AngrYkIdzrUlE View Post
    Here's what i get when i try to display all songs (i.e. choosing "2" in the menu)

    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at SongOrganiser.getAllSongs(SongOrganiser.java:61)
    	at songOrganiserClient.displayAll(songOrganiserClient.java:81)
    	at songOrganiserClient.main(songOrganiserClient.java:22)
    and when i choose "3"
    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at SongOrganiser.findTotalLength(SongOrganiser.java:86)
    	at songOrganiserClient.totalAndAverage(songOrganiserClient.java:91)
    	at songOrganiserClient.main(songOrganiserClient.java:25)
    PS: This is after adding 2 songs to the Array.

    What is the problem there?? Unfortunately i only know how to read compile errors :(
    Java Code:
     // get all songs
       public String getAllSongs() {
          // String heading = "Number  Song Title     Artist         Length";
          String details = "";
          for (int i = 1; i <= count; i++) //
             details = i + "        " + songArr[i].getTitle() + "     "
                   + songArr[i].getArtist() + "         " + songArr[i].getLength();
          return details;
       }
    It has to do with where an array index starts (0) and ends (length - 1). I placed a // where the error is. Change the same thing in all your for loops and it will work. Also look at your deleteSong method. It will always return true unless theres no songs.

  7. #7
    Join Date
    Mar 2009
    Posts
    38
    Rep Power
    0

    Default

    Quote Originally Posted by hawaiian robots View Post
    Java Code:
     // get all songs
       public String getAllSongs() {
          // String heading = "Number  Song Title     Artist         Length";
          String details = "";
          for (int i = 1; i <= count; i++) //
             details = i + "        " + songArr[i].getTitle() + "     "
                   + songArr[i].getArtist() + "         " + songArr[i].getLength();
          return details;
       }
    It has to do with where an array index starts (0) and ends (length - 1). I placed a // where the error is. Change the same thing in all your for loops and it will work. Also look at your deleteSong method. It will always return true unless theres no songs.
    changed it to
    Java Code:
    /get all songs
    
    	
    
    	public String getAllSongs()
    
    	{
    
    		
    
    		//String heading = "Number  Song Title     Artist         Length";
    
    		String details = "";
    
    		for (int i = 0; i <= (songArr.length - 1); i++)
     //changes here!!!!
    			details = i + "        " + songArr[i].getTitle() + "     "+ songArr[i].getArtist()+ "         "+songArr[i].getLength();
    
    			return  details;
    
    			
    
    	}
    still getting the same error :(

    Can you copy all my classes and try to run them on your machine???...it's very depressing these runtime errors :(

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,568
    Rep Power
    12

    Default

    Did you understand what hawaiian robots was saying about the limits of your for loop?

    Your latest version of getAllSongs() says

    Java Code:
    for (int i = 0; i <= (songArr.length - 1); i++)
    If you compare those limits with the picture I posted earlier, you'll see that from 0 to (and including) songArr.length-1 is the entire songArr array. Now some of the array slots are null (have no song in them), so it's no wonder you get the NullPointerException when you try getTitle() and the rest.

    Figure what the for loop limits should really be: the aim is to check all the array slots that are labelled "song" in the diagram I posted.

    (and don't blindly use the code posted by hawaiian robots or anybody else: figure out what the for loop limits should be, and why.)
    Last edited by pbrockway2; 04-17-2009 at 08:26 AM.

  9. #9
    Join Date
    Mar 2009
    Posts
    38
    Rep Power
    0

    Default

    Thanks all for your help, i found the problem, it was when i assigned:
    Java Code:
    for (int i = 0; i <= count; i++)
    it should be be i < count because when i = count is outside the array range.

    Thanks all for the help.

  10. #10
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,568
    Rep Power
    12

Similar Threads

  1. trouble in removing a value
    By jacline in forum New To Java
    Replies: 5
    Last Post: 03-20-2009, 06:56 PM
  2. Trouble with Dr Java.
    By davefanelli in forum New To Java
    Replies: 1
    Last Post: 10-22-2008, 07:20 PM
  3. Got Trouble with JSlider
    By hungleon88 in forum Advanced Java
    Replies: 6
    Last Post: 08-30-2008, 06:02 PM
  4. having some trouble
    By Unknown1369 in forum New To Java
    Replies: 13
    Last Post: 07-22-2008, 12:52 AM
  5. Having trouble with array
    By ice22 in forum New To Java
    Replies: 3
    Last Post: 11-13-2007, 04:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •