Having a bit of trouble moving objects I’ve created into an array.
So what I actually need to do is create objects than move them into an array.
I’m not quite sure what I’m doing wrong.
If you think I should be using a arraylist instead of a array please say so
I made a quick example with less data fields than my actual program but its pretty well the same as my larger problem.
Thank you for your time.
public class Music {
private static String songTitle;
private static double songLength;
private int rating;
public Music(String songTitle, double songLength, int rating) {
// TODO Auto-generated constructor stub
}
public static String getsongTitle()
{
return songTitle;
}
public static double getsongLength()
{
return songLength;
}
public static int rating()
{
return rating();
}
//constructors for music objects
Music song1 = new Music ("song name", 5.32, 10);
Music song2 = new Music ("billy",1.2, 8 );
Music song3 = new Music ("hello", 1.5, 9 );
static //Create array and make posistion 0 = song1
Music[] songDetails = new Music[3];{
songDetails[0] = song1;
}
public static void main(String[] args) {
//print first place in array
System.out.println(songDetails[0]);
}
Edit had a spelling mistake in the code and was missing the word static in the array declaration
Almost everything is OK here 😉 There are many ways. Simply access songDetails from nonstatic method (and change Music fields to nonstatic, and implement Music constructor):
You may also want do it like this:
or this (more readable):
or (more flexible):
COMMENT FOR YOUR EDIT:
the array was static, but initialization was not static. You missed static keyword before initialization block:
and static version with list:
And oh, I see it now, your Music class is broken too. Use instance fields instead of static and assign values in constructor: