如何使用数组累积类字段?

时间:2015-04-06 19:09:35

标签: java object arraylist

当我尝试累积albumPrice字段时,它不会更新。 我需要的是每张专辑更新价格,然后输出totalPaid值。

import java.text.DecimalFormat;
import java.util.ArrayList;

public class ArtistList {
    static DecimalFormat f = new DecimalFormat("$###.00");
    private String artistName = null;
    private Double price = 0.0;
    private String albumName = null;
    private String albumYear = null;
    private Double totalPaid = 0.0;
    private Double priceOut = 0.0;

    ArtistList(String thisArtist, String thisAlbum, String thisYear, double thisPrice) {
        artistName = thisArtist;
        albumName = thisAlbum;
        albumYear = thisYear;
        price = thisPrice;
    }

    public static void main(String[] args) {
        int size = 0;

        ArrayList<ArtistList> artists = new ArrayList<ArtistList>();

        artists.add(new ArtistList("Dave Matthews Band", "Under The Table and Dreaming", "1994", 12.12));
        artists.add(new ArtistList("Stone Temple Pilots", "Core", "1992", 5.99));
        artists.add(new ArtistList("Incubus", "Make Yourself", "1999", 5.89));
        size = artists.size();
        System.out.println("We have " + size + " artists");

        for (ArtistList out : artists) {
            System.out.println(out);
        }

        for (@SuppressWarnings("unused") ArtistList out : artists) {
            priceOut = priceTotal(price);
        }

        // for(@SuppressWarnings("unused") ArtistList out: artists){
        //               totalPaid+=price;
        //  }

        System.out.println();
        System.out.println("Total paid for inventory" + " " + f.format(priceOut));
    }

    public String toString() {
        return artistName + ", " + albumName + ", " + albumYear + ", " + f.format(price);
    }

    public Double priceTotal(Double price) {
        return totalPaid += price;
    }
}

1 个答案:

答案 0 :(得分:1)

当你在类中使用main方法时,它将首先运行,并且不会有自己的类的实例,因此在使用main方法时不会启动私有变量,因此你必须设置它们如果你想使用它们,则为static。

你可以在一个单独的类中分离main方法,然后通知getter和setter私有字段。

Class TestArtistList{
public class ArtistList{
    // TODO declare the fields with getters and setters and the methods
}
public static void main(String[] args) {
    // TODO your test code

    ArrayList<ArtistList> artists = new ArrayList<ArtistList>();

    artists.add(new ArtistList("Dave Matthews Band", "Under The Table and Dreaming", "1994", 12.12));
    artists.add(new ArtistList("Stone Temple Pilots", "Core", "1992", 5.99));
    artists.add(new ArtistList("Incubus", "Make Yourself", "1999", 5.89));
    size = artists.size();
    System.out.println("We have " + size + " artists");

    for (ArtistList out : artists) {
        System.out.println(out);
    }

    for (@SuppressWarnings("unused") ArtistList out : artists) {
        out.priceOut = priceTotal(out.price);
    }
}
}