Reputation: 190
I have two streams extending the FilterInputStream class. A is reading doubles from the stream and B shall take those doubles and apply a random noise on them. The question is about how to implement the second stream correctly, so B has access to the custom function of A returning doubles. The chaining shall be as follows:
Source ----> A ----> double ----> B ----> doubles with noise
Best Regards, Turakar
Upvotes: 0
Views: 126
Reputation: 100279
A FilteredInputStream
seems to be not very suitable for your problem as InputStream
represents a sequence of bytes, but what you need is the sequence of double
numbers. One possible alternative is to implement the Iterator
interface instead. Thus A
would become:
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();
}
}
And B
would become
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();
}
}
These classes can be used in the following manner:
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());
}
Typical output:
1.0
56.0
123.0
30.0
0.0
-0.011797617285828732
55.71721599815757
123.33995522117877
29.16152453760448
-0.9614750776766922
Upvotes: 1