Java Swing Object [] [] getData()混淆

时间:2014-09-11 06:18:59

标签: java arrays

您好我在Java课程中开始学习Swing并开始使用JTable并将数据输入其中时遇到了一些麻烦。这很难解释所以我只是发布我给出的代码以及问题。

问题是: getData()方法需要返回一个Object [] [],其中包含类所代表的数据。

第一堂课是MusicAlbum

class MusicAlbum {
    private String id;
    private String name;
    private String genre;
    private boolean isCompilation;
    private int track_count;

    public MusicAlbum(String id, String name, String genre, boolean isCompilation, int track_count) {
        this.id = id;
        this.name = name;
        this.genre = genre;
        this.isCompilation = isCompilation;
        this.track_count = track_count;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getGenre() {
        return genre;
    }

    public boolean isCompilation() {
        return isCompilation;
    }

    public int getTrackCount() {
        return track_count;
    }

    public boolean equals(Object obj) {
        if (obj instanceof MusicAlbum)
            return this.id.equalsIgnoreCase(((MusicAlbum)obj).id);

        return super.equals(obj);
    }
}

我必须实现方法的类是MusicDataObject(在底部)

import java.util.Random;
import java.util.Scanner;

public class MusicDataObject {
    private List<MusicAlbum> albums = new ArrayList<>();
    private Random random = new Random(); // for generating IDs

    public void addAlbum(MusicAlbum album) throws IllegalArgumentException {
        if (searchAlbum(album.getId()) != null)
            throw new IllegalArgumentException("Album ID is not new!");

        albums.add(album);
    }

    public MusicAlbum searchAlbum(String id) {
        for (MusicAlbum album : albums) {
            if (album.getId().equalsIgnoreCase(id)) {
                return album;
            }
        }

        return null;
    }

    public MusicAlbum removeAlbum(String id) {
        MusicAlbum album = searchAlbum(id);
        albums.remove(album);

        return album;
    }

    public void updateAlbum(MusicAlbum album)
      throws IllegalArgumentException {

        if (removeAlbum(album.getId()) == null)
            throw new IllegalArgumentException("Album ID does not exist!");

        addAlbum(album);
    }

    public String generateID() {
        String formatter = "A%0" + (int)Math.ceil(Math.log10(albums.size() * 2) + 1) + "d";
        String ID;

        do {
            ID = String.format(formatter, random.nextInt(albums.size() * 2 + 1));
        } while (searchAlbum(ID) != null);

        return ID;
    }

    public void saveData(String fileName) throws IOException {
        // make sure that the file exists or try to create it
        File fout = new File(fileName);
        if (!fout.exists() && !fout.createNewFile())
            return;

        PrintWriter out = new PrintWriter(fout);

        for (MusicAlbum album: albums) {
            out.println(serializeAlbum(album));
        }

        out.close();
    }

    public String serializeAlbum(MusicAlbum album) {
        return String.format(
          "%s;%s;%s;%b;%d",
          album.getId(),
          album.getName(),
          album.getGenre(),
          album.isCompilation(),
          album.getTrackCount());
    }

    public void loadFile(String fileName) throws FileNotFoundException {
        albums = new ArrayList<>();
        Scanner in = new Scanner(new File(fileName));

        while (in.hasNext()) {
            // --- split the next line with the character ";"
            String line = in.nextLine();
            String[] tokens = line.split(";");

            // --- construct a new MusicAlbum using the resulting tokens. NOTE: This isn't very robust.
            //      If a line doesn't contain enough data or the data is invalid, this will crash
            albums.add(new MusicAlbum(
              tokens[0],
              tokens[1],
              tokens[2],
              Boolean.parseBoolean(tokens[3]),
              Integer.parseInt(tokens[4])
            ));
        }
    }

    // ----- these methods need to be implemented

    public Object[][] getData() {
        // TODO
    }

    public String[] getColumnNames() {
        // TODO
    }
}

正在使用的样本数据位于txt文件中,格式如下:

A01;反抗;原声;真; 24

A02; Insomniac; Punk Rock; false; 14

A03;比赛的美好日子;吉普赛爵士乐;假; 10

A04; Viva La Internet; Ska; false; 31

A05; New Surrender; Rock; false; 17

所以基本上这是他们希望我实现的getData()方法让我感到悲伤。我不完全理解他们想要我做什么,也不完全理解Object [] []的作用。

我希望我已经足够清楚了,我会感激所有的帮助。另外,请尝试尽可能地解释事情并尽可能地愚弄它们,我是很多新手:)

感谢您的时间。

1 个答案:

答案 0 :(得分:3)

Object[][]是一个二维数组。它的每个元素都是Object[],是一维数组。

您的任务是创建一个二维数组,每个Object[]都有一个元素(MusicAlbum)。 Object[]应该包含MusicAlbumidnamegenreisCompilationtrack_count的属性。

您可以像这样创建一个对象数组:

Object[] arr = new Object[] { "some", "values", 23, true };

你可以像这样创建一个二维数组:

Object[][] arr2d = new Object[size][];

您可以遍历所有MusicAlbum,为每个Object[]创建包含该音乐专辑属性的arr2d,并将其设置为// Set first element: arr2d[0] = arr; // Get first element: Object[] firstElement = arr2d[0];

您可以像设置其他任何数组一样设置/获取二维数组的元素:

getColumnNames()

String[]方法应该只返回一个Object[](一个String数组),其中包含列名,属性名称。

可能很明显,但请注意,返回列名的顺序和属性值的顺序(在{{1}}的元素中)应该是相同的。