2015-04-06 31 views
0

當我試圖積累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; 
    } 
} 
+0

「價格」和「albumPrice」指的是什麼(在ArtistList中)?你的代碼中不包含一行評論... –

+0

道歉...讓它平平。將變量從類字段更改爲在main()中聲明的變量 – dangerouslyCoding

+0

您確定您不會在這裏混淆「Double」和「double」嗎? – Clashsoft

回答

1

當您使用的主要方法的類裏面,它會首先運行和使用的主要方法,因此你的時候也不會成爲一流的IT自身的一個實例,以使私有變量將不啓動如果你想使用它們,必須將它們設置爲靜態。

你可以在單獨的類中分離主要方法,然後通知私有字段的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); 
    } 
} 
}