简体   繁体   中英

Java: Array only prints last element

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.

Try something like this:

public static void main(String[] args)
{
    // create an array for artists
    artist[] artistList = new artist[0];

    // open the original file
    try {
        final File file = new File("p1artists.txt");
        final Scanner input = new Scanner(file);

        while (input.hasNextLine())
        {
            final int id = input.nextInt();
            final String name = input.next();
            // Skip to next line...
            input.netxLine();

            // Create a ne array, with one more element
            final artist[] newList = new artist[artistList.length + 1];
            // Copy the element references to the new array
            System.arraycopy(artistList, 0, newList, 0, artistList.length);
            // create a new artist and put it in the array
            newList[artistList.length] = new artist(id, name);
            // Replace old array with new one
            artistList = newList;
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

   for(artist e : artistList)
        System.out.println(e);
}

Your array is only printing one element because you are getting an exception by trying to write to position 2+, which exits the try block, and skips to the foreach loop.

You only have one element in the array

int totalArtist = 0;
artist[] artistList = new artist[1+totalArtist]; // = new artist[1];

Since you cannot use lists, you can either

  1. Read the number of lines of the file, then create the array. Number of lines in a file in Java
  2. Prompt for the number of artists to read from the file
  3. Emulate a List by creating a new array with a larger sized array yourself and copying elements over

Your artistList.length is always 1. And hence you are always be updating the first and only element. Array can't be extended dynamically. To achieve what you wanted consider ArrayList or LinkedList depending how you foresee the way you consume the items in your resulting list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM