我有两个扩展FilterInputStream类的流。A从流中读取双精度,B取这些双精度并对它们施加随机噪声。问题是关于如何正确实现第二个流,这样B就可以访问A返回双精度的自定义函数。链接方式如下:
源-> ->双-> B——>双打与噪声
向Turakar致以最诚挚的问候
A FilteredInputStream
似乎不太适合您的问题,因为InputStream
表示字节序列,但您需要的是double
数字序列。一种可能的替代方法是实现Iterator
接口。因此,A
将变成:
import java.io.InputStream;
import java.util.Iterator;
import java.util.Scanner;
public class DoubleIterator implements Iterator<Double> {
private Scanner scanner;
public DoubleIterator(InputStream is) {
scanner = new Scanner(is);
}
@Override
public boolean hasNext() {
return scanner.hasNextDouble();
}
@Override
public Double next() {
return scanner.nextDouble();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
而B
会变成
import java.util.Iterator;
import java.util.Random;
public class NoiseIterator implements Iterator<Double> {
Random r = new Random();
private Iterator<Double> source;
public NoiseIterator(Iterator<Double> source) {
this.source = source;
}
@Override
public boolean hasNext() {
return source.hasNext();
}
@Override
public Double next() {
return source.next()+r.nextGaussian();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
这些类可以按以下方式使用:
String s = "1 56 123 30 0";
Iterator<Double> it = new DoubleIterator(new ByteArrayInputStream(s.getBytes()));
while(it.hasNext()) {
System.out.println(it.next());
}
it = new NoiseIterator(new DoubleIterator(new ByteArrayInputStream(s.getBytes())));
while(it.hasNext()) {
System.out.println(it.next());
}
典型输出:1.0
56.0
123.0
30.0
0.0
-0.011797617285828732
55.71721599815757
123.33995522117877
29.16152453760448
-0.9614750776766922