I've been stuck on this assignment for hours and I can't figure this out. I create an array of artists with a size defined by a variable which I increase as more artists get added. If I set the artist[] artistList = new artist[totalArtist];
, I get an arrayoutofbounds or just a blank output, so doing artist[] artistList = new artist[1+totalArtist];
works for me so far and at least gives me an output. Any improvements would be nice
Here is a snippet of my code:
public static void main(String[] args) {
//initialize total artists and id
int totalArtist = 0;
int newID = 0;
//create an array for artists
artist[] artistList = new artist[1+totalArtist];
//open the original file
try {
File file = new File("p1artists.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
int id = input.nextInt();
String name = input.next();
//create a new artist and put it in the array
for (int i = 0; i < artistList.length; i++) {
artistList[i] = new artist(id, name);
totalArtist++;
}
//increment to a newID
newID = id + 1;
}
} catch (IOException e) {
e.printStackTrace();
}
for(artist e : artistList)
System.out.println(e);
My main problem is: Within the for loop, I am able to create a new artist and put it in the artistList array. I am also able to print every element. However, outside the try-catch, it only prints the last element once. I don't understand what I am doing wrong for this to happen.
Please do not suggest array list because if i were able to do it for this assignment, I obviously would.