我有两个扩展FilterInputStream类的流。 A正在从流中读取双打,B将采用那些双打并对它们施加随机噪声。问题是如何正确实现第二个流,因此B可以访问A返回双精度的自定义函数。链接应如下:
来源----> A ---->双----> B ---->噪音加倍
最诚挚的问候,Turakar
答案 0 :(得分:1)
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