如果您想直接找到问题,请跳过本段。在实践中,我试图编写一个模拟经济的Java程序,并为此写了一个公司类。这个想法就是说,其中有十几个将他们的收入包括在一个正常的变量函数中,那就是经济。从另一个类访问实例变量
我写了一个单独的类来使用JFreeChart绘制公司的输出图。但是,我无法访问ArrayList,我从图表类中每年写入大量金钱。我明白最好的方法是使用getter,但这似乎不起作用,所以如果这是您的建议,请您举个例子吗?谢谢!
公司:
public class ServiceProvider implements Company {
//Variables
public ArrayList getRecords(){
return records;
}
public ServiceProvider(){
money = 10000;
yearID = 0;
goodYears = 0;badYears = 0;
records = new ArrayList();
id++;
}
public void year() {
yearID++;
if(!getBankrupt()){
spend();
}
writeRecords();
}
public void spend() {
...
}
public void printRecords() {
for(int i=0;i<records.size();i++){
String[] tmp = (String[]) records.get(i);
for(String a:tmp){
System.out.print(a+" ");
}
System.out.print("\n");
}
}
public void writeRecords(){
String[] toWrite = new String[2];
toWrite[0] = String.valueOf(yearID);
toWrite[1] = String.valueOf(money);
records.add(toWrite);
}
public void writeRecords(String toWrite){
String temp = "\n"+yearID+" "+toWrite;
records.add(temp);
}
public boolean getBankrupt(){
boolean result = (money < 0) ? true : false;
return result;
}
}
我想从访问:
public class grapher extends JFrame {
ArrayList records = s.getRecords();
public grapher(){
super("ServiceProvider");
final XYDataset dataset = getCompanyData();
}
private XYDataset getCompanyData(){
XYSeries series;
for(int i=0;i<s.getRecords().length;i++){ //S cannot be resolved, it's instantiated in the main class.
}
}
}
主类:
public class start {
public static void main(String[] args) {
ServiceProvider s = new ServiceProvider();
for(int i=0;i<10;i++){
s.year();
}
s.printRecords();
}
}
附:别告诉我记录是多么糟糕。我知道。
所有代码中有多少与问题相关?请编辑并删除所有与该问题无关的代码。更好的是,提供例如'ClassA','ClassB'等示例代码 - 参见[SSCCE](http://sscce.org) – Bohemian