Java:数组仅打印最后一个元素

标签 java arrays

我在这项任务上已经被困了几个小时,但我无法弄清楚这一点。我创建了一个艺术家数组,其大小由变量定义,随着更多艺术家的添加,该数组的大小也会增加。如果我设置artist[]artistList=newartist[totalArtist];,我会得到一个arrayoutofbounds或只是一个空白输出,所以artist[]artistList=newartist[1+totalArtist] ; 到目前为止对我有用,至少给了我一个输出。任何改进都会很好

这是我的代码片段:

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);

我的主要问题是:在for循环中,我能够创建一个新的艺术家并将其放入artistList数组中。我还可以打印每个元素。然而,在 try-catch 之外,它只打印最后一个元素一次。我不明白我做错了什么才会发生这种情况。

请不要建议数组列表,因为如果我能够完成此作业,我显然会这样做。

最佳答案

尝试这样的事情:

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);
}

关于Java:数组仅打印最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46249821/

相关文章:

Java:抛出和捕获异常以验证输入的正确方法

jquery - 如何使用 jQuery 循环遍历数组?

javascript - 生成一组唯一的 N 个随机数,如果所有数字加起来等于 N

使用十六进制值创建字符数组

java - JOptionPane 打开时是否可以暂停当前线程?

java - 如何使用jsp或servlet或java将excel中的大量信息更新到oracle数据库

java - Tomcat的webdav在Mac OS X上部署时重复401

java - BlackBerry 数学实用程序(Pow & Round)

c++ - 如何用 NULL 填充指针数组?

java - 在数组的数组中查找模式