public class NumberCache
{
private RandomNumberGenerator generator;
public NumberCache(RandomNumberGenerator rng)
{
generator = rng;
}
private int index;
private double[] cache = new double[0];
public synchronized double retrieveNext()
throws RandomNumberGeneratorException
{
// Hinzugefügt
if (generator == null)
{
String msg = "No RandomNumberGenerator available.";
throw new RandomNumberGeneratorException(msg);
}
if (index >= cache.length)
{
cache = generator.nextBatch();
index = 0;
if ((cache == null) || (cache.length <= 0))
{
String msg = "The RandomNumberGenerator (" +
generator + ") returned nothing";
throw new RandomNumberGeneratorException(msg);
}
}
return cache[index++];
}
public String toString()
{
StringBuffer result = new StringBuffer(1024);
result.append("NumberCache { id=");
result.append(super.toString());
result.append(", index=");
result.append(index);
if (cache == null)
{
result.append(", cache=null");
}
else
{
for (int i = 0; i < cache.length; ++i)
{
result.append(", cache[");
result.append(i);
result.append("]=");
result.append(cache[i]);
}
}
result.append(", generator=");
result.append(generator);
result.append("}");
return result.toString();
}
public static void printRandom(RandomNumberGenerator rng, int count)
throws RandomNumberGeneratorException
{
NumberCache cache = new NumberCache(rng);
for (int i = 0; i < count; i++)
{
System.out.println(cache);
System.out.println(cache.retrieveNext());
}
}
} |