我在总结我在班级ArrayList
中在班级Treasureroom
中所做的Accountant
时遇到麻烦。如下面的代码所示,我有一个ArrayList
,类型为Valuable
。我需要能够总结int
类中的所有Accountant
元素。
会计
package Accountant;
import java.util.Iterator;
import java.util.Random;
import ValuableFactory.Valuable;
import rw.RWMonitor;
import rw.Treasureroom;
public class Accountant implements Runnable {
private Treasureroom treasureroom;
private static final int MAX_WAIT_TIME = 10000; // 3 seconds
private static final int MAX_WORK_TIME = 5000; // 2 seconds
private static final Random random = new Random();
private int no;
private RWMonitor monitor;
private Treasureroom resource;
public Accountant( int no, RWMonitor monitor, Treasureroom resource ) {
this.no = no;
this.monitor = monitor;
this.resource = resource;
}
public void run() {
while(true) {
try {
Thread.sleep(random.nextInt(WAIT_TIME));
}
catch (InterruptedException ex) {
}
System.out.println("Accountant counts: " + resource);
monitor.acquireRead();
//System.out.println("Accountant counted: " + valuable);
try {
Thread.sleep(random.nextInt(MAX_WAIT_TIME));
}
catch (InterruptedException ex) {
}
for (int i = 0; i > resource.)
System.out.println("Accountant counted: " + resource.getValueRead());
monitor.releaseRead();
try {
Thread.sleep(random.nextInt(WAIT_AGAIN));
}
catch (InterruptedException ex) {
// TODO: handle exception
}
}
}
//System.out.println("The total sum of TreasureRoom is " + Thread.currentThread().getName());
//TreasureRoom.releaseRead();
}
藏宝室
package rw;
import java.util.*;
import ValuableFactory.*;
public class Treasureroom {
ArrayList<Valuable> valuables = new ArrayList<Valuable>();
public Valuable getValueWriter() {
return valuables.remove(0);
}
public void updateValue(Valuable valuable) {
valuables.add(valuable);
}
public boolean removeValue(Valuable valuable) {
return valuables.remove(valuable);
}
public Valuable getValueReade() {
for (int i=0; i<valuables.size();i++) {
return valuables.get(i);
}
return null;
}
}
有价值
package ValuableFactory;
public class Valuable implements ValuableFactory {
private String name;
private int value;
public Valuable(String name, int value) {
this.name = name;
this.value = value;
}
@Override
public String getName() {
return name;
}
@Override
public int getValue() {
return value;
}
}
最佳答案
您的Accountant
类在其构造函数中实例化Treasureroom
对象,这意味着要使用ArrayList
对象在Treasureroom
对象内循环遍历Accountant
,您将需要Accountant
中的方法,该方法在Treasureroom
。
会计
public int getTreasureSum()
{
return resource.sumTreasure();
}
藏宝室
public int sumTreasure()
{
int sum = 0;
for(int i = 0; i < valuables.size(); i++)
{
sum+= valuables.get(i).getValue();
}
return sum;
}
同样在您的
Accountant
类中,您还有一个未使用的Treasureroom
对象private Treasureroom treasureroom;