Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a class that extends Reader, and provides a new kind of Reader, a TrReade

ID: 3598471 • Letter: C

Question

Create a class that extends Reader, and provides a new kind of Reader, a TrReader, that translates the characters from another Reader. That is, a TrReader’s source of characters is some other Reader, which was given to the TrReader’s construc- tor. The TrReader’s read routine simply passes on this other Reader’s characters, after first translating them.

import java.io.Reader;

/** Translating Reader: a stream that is a translation of an
* existing reader. */
public class TrReader extends Reader {
/** A new TrReader that produces the stream of characters produced
* by STR, converting all characters that occur in FROM to the
* corresponding characters in TO. That is, change occurrences of
* FROM.charAt(0) to TO.charAt(0), etc., leaving other characters
* unchanged. FROM and TO must have the same length. */
public TrReader(Reader str, String from, String to) {
// FILL IN
}

// FILL IN
// NOTE: Until you fill in the right methods, the compiler will
// reject this file, saying that you must declare TrReader
// abstract. Don't do that; define the right methods instead!
}

Explanation / Answer

public class TrReader extends Reader {

private final Reader reader;

private final String from;

private final String to;

/** A new TrReader that produces the stream of characters produced

* by STR, converting all characters that occur in FROM to the

* corresponding characters in TO. That is, change occurrences of

* FROM.charAt(0) to TO.charAt(0), etc., leaving other characters

* unchanged. FROM and TO must have the same length. */

public TrReader(Reader str, String from, String to) {

this.reader = str;

this.from = from;

this.to = to;

}

public void close() throws IOException {

this.reader.close();

}

private char convertChar(char c) {

int newC = this.from.indexOf(c);

if (newC == -1) {

return c;

}

return this.to.charAt(newC);

}

@Override

public int read(char[] cbuf, int off, int len) throws IOException {

int actualRead = this.reader.read(cbuf, off, len);

for (int i = off; i < off + actualRead; i += 1) {

cbuf[i] = convertChar(cbuf[i]);

}

return actualRead;

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote