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

Need help with java Translator class to implement what\'s in the Translator diag

ID: 3911150 • Letter: N

Question

Need help with java Translator class to implement what's in the Translator diagram.

Making a morse code from english files to morse code files.

Here is my code so far.

---------------------------------Main.java--------------------------------

package morsecodeplayer;

public class Main {

public static void main(String[] args)

{

Translator translator = new Translator("test.mor");

translator.translate();

}

}

---------------------------------MorseCodePlayer.java--------------------------------

package morsecodeplayer;

import javax.sound.sampled.*;

public class MorseCodePlayer {

public static float SAMPLE_RATE = 8000f;

public static void dot()

throws LineUnavailableException

{

tone(1000, 75);

}

public static void dash()

throws LineUnavailableException

{

tone(500, 116);

}

public static void tone(int hz, int msecs)

throws LineUnavailableException

{

byte[] buf = new byte[1];

AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, false);   

SourceDataLine sdl = AudioSystem.getSourceDataLine(af);

sdl.open(af);

sdl.start();

for (int i=0; i < msecs*8; i++) {

double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;

buf[0] = (byte)(Math.sin(angle) * 127.0 * 1);

sdl.write(buf,0,1);

}

sdl.drain();

sdl.stop();

sdl.close();

}

public static void play(String morseChar)

{

try

{

for (int i = 0; i < morseChar.length(); ++i)

{

if(Character.toString(morseChar.charAt(i)).equals("."))

dot();

else

dash();

}

}

catch(LineUnavailableException ex)

{

System.out.println("Error playing the file.");

}

}

}

---------------------------------Translator.java--------------------------------

package morsecodeplayer;

public class Translator
{

}

Assignment The translator program adheres to the following rules: English message files will be stored as text files, one sentence per line Morse code message files will be stored as text files, one encoded character per line, where end of words are indicated by one blank line, and end of sentences are indicated by two blank lines. English message files will contain file extension eng, and Morse code files with have file extension mor The additional assumption for this project is that: Messages will contain only lowercase characters, periods, commas, question marks, dashes, and apostrophes. Morse Code Translator for the main program is given on t he next page. Note, read the The UML design diagram following description carefully to be sure you understand what is being shown. Translator Translator(inputFile: string) void nputBuffer Ou uffer utBufferinputFile: string) OfBuffer): boolean Buffer(outputFle: string) etReader): Scanner Writer): PrintWriter void : void ToWhite: sring):void isEndOrWord) :boolean void tBuffer tBuffer Eng lishlnputBuffer oken: string MorselnputBuffer string -EnglishOutputBufferOutp File : string) string) int ToWrite: string): void ToWrite: string) void void void ishinputBuffer(inputFile: string)EnglishinputBufer(inputFile: string) Char(): MsgChar ):bodlean ): boolear Powered By Visual Paradgm Community Edion

Explanation / Answer

main.java

public class Main {

   public static void main(String[] args)
   {
       Translator translator = new Translator("test.mor");
       translator.translate();
   }
}


Translator.java

public class Translator {

    /**
     * Indicates if we are translating to or from morse.
     */
    private boolean toMorse;

    /**
     * Input and output streams for processing data.
     */
    private InputBuffer input;
    private OutputBuffer output;

    public Translator(String inputFile) {

        // Determining if we are translating to morse or not
        int fileNameLength = inputFile.length();
        String extension = inputFile.substring(fileNameLength - 3);
        switch (extension) {
            case "mor":
                System.out.println("Translating to English");
                toMorse = false;
                break;
            case "eng":
                System.out.println("Translating to Morse");
                toMorse = true;
                break;
            default:
                System.out.println("The file type provided is not supported!");
                System.exit(-1);
                break;
        }

        if (toMorse) {
            input = new EnglishInputBuffer(inputFile);
            output = new MorseOutputBuffer("output.mor");
        } else {
            input = new MorseInputBuffer(inputFile);
            output = new EnglishOutputBuffer("output.eng");
        }
    }

    /**
     * Handles the translation of files. Input and output.
     */
    public void translate() {

        do {
            String stringInput = input.getChar().convert();

            if (input.isEndOfWord()) {
                output.putChar(stringInput);
                output.markEndOfWord();
            } else if (input.isEndOfSentence()) {
                output.markEndOfSentence();
            } else {
                output.putChar(stringInput);
                if (toMorse) {
                    MorseCodePlayer.play(stringInput);
                }

            }

        } while (!input.endOfBuffer());

        input.close();
        output.close();
    }
}


InputBuffer.java

package com.company;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public abstract class InputBuffer {

    private Scanner reader = null;

    public InputBuffer(String inputFile) {

        try {
            FileInputStream fileInputStream = new FileInputStream(inputFile);
            reader = new Scanner(fileInputStream);
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + inputFile);
            System.exit(-1);
        }
    }

    public boolean endOfBuffer() {
        if (reader.hasNext()) {
            return false;
        } else {
            return true;
        }
    }

    public Scanner getReader() {
        return reader;
    }

    public void close() {
        try {
            reader.close();
        } catch (Exception e) {
            System.out.println("There was a problem closing the file: " + e);
            System.exit(-1);
        }
    }

    public abstract MsgChar getChar();

    public abstract boolean isEndOfWord();

    public abstract boolean isEndOfSentence();

}


MorseCodePlayer.java

package com.company;

import javax.sound.sampled.*;

public class MorseCodePlayer {

public static float SAMPLE_RATE = 8000f;

public static void dot()
     throws LineUnavailableException
{
     tone(1000, 75);
}

public static void dash()
     throws LineUnavailableException
{
     tone(1000, 225);
}
public static void tone(int hz, int msecs)
      throws LineUnavailableException
{
    byte[] buf = new byte[1];
    AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, false);    
    SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
    sdl.open(af);
    sdl.start();
    for (int i=0; i < msecs*8; i++) {
      double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
      buf[0] = (byte)(Math.sin(angle) * 127.0 * 1);
      sdl.write(buf,0,1);
    }
    sdl.drain();
    sdl.stop();
    sdl.close();
}

public static void play(String morseChar)
{
      try
      {
          for (int i = 0; i < morseChar.length(); ++i)
          {
              if(Character.toString(morseChar.charAt(i)).equals("."))
                  dot();
              else
                  dash();
          }
      }
      catch(LineUnavailableException ex)
      {
          System.out.println("Error when attempting to play file.");
      }
}
}

MorseChar.java

package com.company;

/**
* Represents a morse character.
*/
public class MorseChar extends MsgChar{

    private String[] englishChars = "abcdefghijklmnopqrstuvwxyz.,-'?".split("");
    private String[] morseChars = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. .-.-.- --..-- -...- .----. ..--..".split(" ");

    public MorseChar(String charValue) {
        super(charValue);
    }

    public String convert() {

        String strToConvert = this.getChar();

        for (int i = 0; i < morseChars.length; i++) {
            if (strToConvert.equals(morseChars[i])) {
                return englishChars[i];
            }
        }

        if (strToConvert.equals("")) {
            return "";
        }

        return "---Broken in English convert---";
    }
}

MorseInputBuffer.java

package com.company;

import java.util.Scanner;

public class MorseInputBuffer extends InputBuffer {

    private String previousLine = "";
    private String currentLine = "";

    public MorseInputBuffer(String inputFile) {
        super(inputFile);
    }

    public MsgChar getChar() {

        Scanner scanner = this.getReader();
        previousLine = currentLine;
        MorseChar myChar = new MorseChar(scanner.nextLine());
        currentLine = myChar.getChar();

        return myChar;
    }

    public boolean isEndOfWord() {
        return currentLine.isEmpty() && !previousLine.isEmpty();
    }

    public boolean isEndOfSentence() {
        return currentLine.isEmpty() && previousLine.isEmpty();
    }
}

MorseOutputBuffer.java

package com.company;

public class MorseOutputBuffer extends OutputBuffer {

    public MorseOutputBuffer(String outputFile) {
        super(outputFile);
    }

    public void putChar(String charToWrite) {
        if (charToWrite.equals(System.lineSeparator())) {
            this.getWriter().print(System.lineSeparator());
            System.out.print(System.lineSeparator());
        } else if (charToWrite.equals(System.lineSeparator() + System.lineSeparator())) {
            this.getWriter().print(System.lineSeparator() + System.lineSeparator());
            System.out.print(System.lineSeparator() + System.lineSeparator());
        } else {
            this.getWriter().print(charToWrite);
            this.getWriter().print(System.lineSeparator());
            System.out.print(charToWrite);
            System.out.print(System.lineSeparator());
        }


    }

    public void markEndOfWord() {
        putChar(System.lineSeparator());
    }

    public void markEndOfSentence() {
        putChar(System.lineSeparator() + System.lineSeparator());
    }
}


MsgChar.java

package com.company;

public abstract class MsgChar {
    private String charValue;

    public MsgChar(String charValue) {
        this.charValue = charValue;
    }

    public String getChar() {
        return this.charValue;
    }

    public abstract String convert();
}


EnglishChar.java

package com.company;

public class EnglishChar extends MsgChar {

    private String[] englishChars = "abcdefghijklmnopqrstuvwxyz.,-'?".split("");
    private String[] morseChars = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. .-.-.- --..-- -...- .----. ..--..".split(" ");

    public EnglishChar(String charValue) {
        super(charValue);
    }

    public String convert() {

        String myChar = this.getChar();

        for (int i = 0; i < morseChars.length; i++) {
            if (myChar.equals(englishChars[i])) {
                return morseChars[i];
            }
        }

        return "---Broken in morse convert---";
    }
}


EnglishInputBuffer.java

package com.company;

import java.util.Scanner;

public class EnglishInputBuffer extends InputBuffer {

    /**
     * Variables to store the token received and which position we are translating.
     */
    private String currentToken = "";
    private int currentPosition = 0;
    private boolean resetToken = true;

    public EnglishInputBuffer(String inputFile) {
        super(inputFile);
    }

    public MsgChar getChar() {

        Scanner scanner = this.getReader();

        if (resetToken) {
            currentToken = scanner.next();
            currentPosition = 0;
            resetToken = false;
        }

        if (currentToken.length() - 1 == currentPosition) {
            String[] toReturnArray = currentToken.split("");
            resetToken = true;
            return new EnglishChar(toReturnArray[currentPosition]);
        }

        String[] toReturnArray = currentToken.split("");
        String toReturn = toReturnArray[currentPosition];

        currentPosition ++;

        return new EnglishChar(toReturn);
    }

    public boolean isEndOfWord() {
        return resetToken;
    }

    public boolean isEndOfSentence() {
        String[] toReturnArray = currentToken.split("");

        if (toReturnArray[currentToken.length() - 1].equals(".") || toReturnArray[currentToken.length() - 1].equals("?")) {
            return currentToken.length() - 1 == currentPosition;
        }
        return false;
    }
}


EnglishOutputBuffer.java

package com.company;

public class EnglishOutputBuffer extends OutputBuffer {

    public EnglishOutputBuffer(String outputFile) {
        super(outputFile);
    }

    public void putChar(String charToWrite) {
        this.getWriter().print(charToWrite);
        System.out.print(charToWrite);
    }

    public void markEndOfWord() {
        putChar(" ");
    }

    /**
     * Provides the formatting for outputting the end of a sentence to the file.
     */
    public void markEndOfSentence() {
        putChar(System.lineSeparator());
    }
}

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