简体   繁体   English

Java:数组仅显示最后一个元素

[英]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]; 如果我设置artist[] artistList = new artist[totalArtist]; , I get an arrayoutofbounds or just a blank output, so doing artist[] artistList = new artist[1+totalArtist]; ,我得到arrayoutofbounds或只是空白输出,所以执行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. 我的主要问题是:在for循环中,我可以创建一个新艺术家,并将其放入artistList数组中。 I am also able to print every element. 我也能够打印每个元素。 However, outside the try-catch, it only prints the last element once. 但是,在try-catch之外,它仅将最后一个元素打印一次。 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. 您的数组仅打印一个元素,因为尝试写入位置2+会得到异常,这会退出try块,并跳转到foreach循环。

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 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. 您的artistList.length始终为1。因此,您始终在更新第一个也是唯一的元素。 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. 要实现您想要的目标,请考虑ArrayList或LinkedList,具体取决于您如何预见消费结果列表中项目的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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