gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:41:36 24 4
gpt4 key购买 nike

当我尝试累积 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;
}
}

最佳答案

当你在类中使用main方法时,它会先运行,并且它自身不会有类的实例,因此在使用main方法时不会初始化私有(private)变量,因此你必须设置它们静态,以防您想使用它们。

您可以将 main 方法分离到一个单独的类中,然后通知私有(private)字段的 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);
}
}
}

关于java - 如何使用数组累积类字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com