SlideShare a Scribd company logo
The Morse code (see Table 6.10 in book) is a common code that is used to encode messages
consisted of letters and digits. Each letter consists of a series of dots and dashes; for example, the
code for the letter a is *- and the code for the letter b is -***. Store each letter of the alphabet in a
node of a binary tree of level 5. The root node is at level 1 and stores no letter. The left node at
level 2 stores the letter e (code is *), and the right node stores letter t (code is -). The 4 nodes at
level 3 store the letters with codes (**, *-, -*, --). To build the tree (see Figure 6.38 in book),
read a file in which each line consists of a letter followed by its code. The letters should be
ordered by tree level. To find the position for a letter in the tree, scan the code and branch left for
a dot and branch right for a dash. Encode a message by replacing each letter by its code symbol.
Then decode the message using the Morse code tree. Make sure you use a delimiter symbol
between coded letters.
Implementation Notes: You will need to complete the generic implementation of the BinaryTree
data structure first (see slides). Once it is complete, solve the problem above (note that the book
uses dots and dashes, we will use the asterisk (*) as the dot, hyphen (-) as a dash, and space ( ) as
the delimiter symbol between coded letters). Provide a menu program that asks the user to 1) test
output for all morse code letters with their respective translated alphabet letters (make sure you
are using the binary tree to do the actual translation, output as a nicely formatted table), 2) enter
an input file name to decode morse code and output the translated text to the screen, or 3) enter
in a line of morse code through the console to decode morse code and output the translated text
to the screen
relevenat picture of both the tree diagram and the table of morse code
Solution
JAVA CODE:
import java.io.*;
import java.util.*;
public class MorseCoder implements MorseCodeInterface {
private MorseNode root;
/**
* constructor to build the tree
*/
public MorseCoder() {
root = new MorseNode();
readTreeInfo();
}
/**
* reads in the tree info from the text file (helper method)
*/
private void readTreeInfo() {
Scanner input = null;
try {
input = new Scanner(new File("encodings.txt"));
} catch (FileNotFoundException exception) {
System.out.println("File not found!");
}
while (input.hasNextLine()) {
String data = input.nextLine().trim();
if (data.length() > 0) {
add(data.substring(1).trim(), data.charAt(0));
}
}
input.close();
}
/**
* adds the letter to the tree based on the mcode string (helper method)
* @param mcode the string being fed in
* @param ltr the letter being added at the node
*/
private void add(String mcode, char ltr) {
MorseNode current = root;
String signal = " ";
for (int i = 0; i < mcode.length(); i++) {
signal = mcode.substring(i, i + 1);
if (signal.equals(".")) {
if (current.getLeft() != null) {
current = current.getLeft();
} else {
current.setLeft(new MorseNode());
current = current.getLeft();
}
} else {
if (current.getRight() != null) {
current = current.getRight();
} else {
current.setRight(new MorseNode());
current = current.getRight();
}
}
}
current.setLetter(ltr);
}
/**
* prints out inorder tree contents
*/
public void inOrderPrint() {
MorseNode current = root;
printInorder(current);
}
/**
* called by inOrderPrint to print tree contents (helper method)
* @param current the node to print
*/
private void printInorder(MorseNode current) {
if (current != null) {
printInorder(current.getLeft());
System.out.print(current.getLetter());
printInorder(current.getRight());
}
}
/**
* decodes a String of morse code to English
* @param str String of morse code
* @return result String of English
*/
public String decode(String str) {
String signal = "";
StringBuffer result = new StringBuffer("");
MorseNode current = root;
for (int i = 0; i < str.length(); i++) {
signal = str.substring(i, i + 1);
if (signal.equals(".")) {
if (current.getLeft() != null) {
current = current.getLeft();
} else {
current.setLeft(new MorseNode());
current = current.getLeft();
}
} else if (signal.equals("-")) {
if (current.getRight() != null) {
current = current.getRight();
} else {
current.setRight(new MorseNode());
current = current.getRight();
}
} else {
result = result.append(current.getLetter());
current = root;
}
}
result = result.append(current.getLetter());
return result.toString();
}
/**
* decodes a String of English to morse code
* @param str String of English
* @return result String of morse code
*/
public String encode(String str) {
MorseNode current = root;
String result = "";
String s = "";
char ltr;
for (int i = 0; i < str.length(); i++) {
ltr = str.charAt(i);
result = searchTree(current, ltr, s);
}
return result;
}
/**
* searches the tree for the letter(s) being inputed and outputs a string of morse (helper
method)
* @param current the node of the tree
* @param ltr the letter being searched for in the tree
* @param s the String being used to build the morse code
* @return the morse code corresponding to the item being checked
*/
public String searchTree(MorseNode current, char ltr, String s) {
char temp = current.getLetter(); //for debugging purposes
if (current.getLetter() == ltr) {
return s;
} else {
if (current.getLeft() != null) {
return searchTree(current.getLeft(), ltr, s + ".");
}
if (current.getRight() != null) {
return searchTree(current.getRight(), ltr, s + "-");
}
return s;
}
}
}
/*Interface*/
public interface MorseCodeInterface {
void inOrderPrint();
String decode(String str);
String encode(String str);
}
/**
* Node class to use with morsecode tree. Do not modify this class.
*/
public class MorseNode {
/** a letter of the alphabet */
private char letter;
/** reference to the left child */
private MorseNode left;
/** reference to the right child */
private MorseNode right;
/** value of letter if empty (not set) */
public static final char EMPTY = ' ';
/*** Default constructor, actual values are set in the MorseCode constructor*/
public MorseNode() {
letter = EMPTY;
left = null;
right = null;
}
/**
* Gets letter contained in node
* @return String - letter value
*/
public char getLetter() {
return letter;
}
/**
* Sets letter in node
* @param String - letter to set
*/
public void setLetter(char letter) {
this.letter = letter;
}
/**
* Gets the node refrenced by left
* @return MorseNode - left
*/
public MorseNode getLeft() {
return left;
}
/**
* Sets left refrence
* @param left - refrence to the node to set
*/
public void setLeft(MorseNode left) {
this.left = left;
}
/**
* Gets the node refrenced by right
* @return MorseNode - right
*/
public MorseNode getRight() {
return right;
}
/**
* Sets right refrence
* @param right - refrence to the node to set
*/
public void setRight(MorseNode right) {
this.right = right;
}}
public class MorseMain {
public static void main(String[] args) {
//Do not modify this file.
MorseCoder mc = new MorseCoder();
mc.inOrderPrint();
// sos decode
System.out.println("Decode Test 1");
String str = "... --- ...";
System.out.println("str = " + str);
System.out.println("str should decode to: sos");
System.out.println("decode(str) = " + mc.decode(str));
testResults("sos", mc.decode(str));
// abcdef...xyz decode
System.out.println("Decode Test 2");
str = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -."
+ " --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..";
System.out.println("str = " + str);
System.out.println("str should decode to: abcdefghijklmnopqrstuvwxyz");
System.out.println("decode(str) = " + mc.decode(str));
testResults("abcdefghijklmnopqrstuvwxyz", mc.decode(str));
// helpmeobiwanyouremyonlyhope decode
System.out.println("Decode Test 3");
str = ".... . .-.. .--. -- . --- -... .. .-- .- -. -.-- --- ..-"
+ " .-. . -- -.-- --- -. .-.. -.-- .... --- .--. .";
System.out.println("str = " + str);
System.out.println("str should decode to: helpmeobiwanyouremyonlyhope");
System.out.println("decode(str) = " + mc.decode(str));
testResults("helpmeobiwanyouremyonlyhope", mc.decode(str));
// --.. encode
System.out.println("Encode Test 1");
str = "z";
System.out.println("str = " + str);
System.out.println("str should encode to: --..");
System.out.println("encode(str) = " + mc.encode(str));
testResults("--..", mc.encode(str));
// ... --- ... encode
System.out.println("Encode Test 2");
str = "sos";
System.out.println("str = " + str);
System.out.println("str should encode to: ... --- ...");
System.out.println("encode(str) = " + mc.encode(str));
testResults("... --- ...", mc.encode(str));
// .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -. encode
System.out.println("Encode Test 3");
str = "runforrestrun";
System.out.println("str = " + str);
System.out.println("str should encode to: .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.");
System.out.println("encode(str) = " + mc.encode(str));
testResults(".-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.", mc.encode(str));
}
/**
* Tests if the output string matches the expected.
* Prints "Test: Passed" if they match, otherwise prints "Test: Failed"
* @param one String - Expected output
* @param two String - Encoded/Decoded call
*/
public static void testResults(String one, String two) {
if(one.trim().equals(two.trim()))
System.out.println("Test: Passed");
else
System.out.println("Test: Failed");
System.out.println();
}
}
INPUT:
encodings.txt :
a .-
b -...
c -.-.
d -..
e .
f ..-.
g --.
h ....
i ..
j .---
k -.-
l .-..
m --
n -.
o ---
p .--.
q --.-
r .-.
s ...
t -
u ..-
v ...-
w .--
x -..-
y -.--
z --..
OUTPUT:
Sample output:
h
s
v
i
f
u
e
l
r
a
p
w
j
b
d
x
n
c
k
y
t
z
g
q
m
o
Decode Test 1
str = ... --- ...
str should decode to: sos
decode(str) = sos
Test: Passed
Decode Test 2
str = .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..
str should decode to: abcdefghijklmnopqrstuvwxyz
decode(str) = abcdefghijklmnopqrstuvwxyz
Test: Passed
Decode Test 3
str = .... . .-.. .--. -- . --- -... .. .-- .- -. -.-- --- ..- .-. . -- -.-- --- -. .-.. -.-- .... --- .--. .
str should decode to: helpmeobiwanyouremyonlyhope
decode(str) = helpmeobiwanyouremyonlyhope
Test: Passed
Encode Test 1
str = z
str should encode to: --..
encode(str) = --..
Test: Passed
Encode Test 2
str = sos
str should encode to: ... --- ...
encode(str) = ... --- ...
Test: Passed
Encode Test 3
str = runforrestrun
str should encode to: .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.
encode(str) = .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.
Test: Passed
/**
* Node class to use with morsecode tree. Do not modify this class.
*/
public class MorseNode {
/** a letter of the alphabet */
private char letter;
/** reference to the left child */
private MorseNode left;
/** reference to the right child */
private MorseNode right;
/** value of letter if empty (not set) */
public static final char EMPTY = ' ';
/*** Default constructor, actual values are set in the MorseCode constructor*/
public MorseNode() {
letter = EMPTY;
left = null;
right = null;
}
/**
* Gets letter contained in node
* @return String - letter value
*/
public char getLetter() {
return letter;
}
/**
* Sets letter in node
* @param String - letter to set
*/
public void setLetter(char letter) {
this.letter = letter;
}
/**
* Gets the node refrenced by left
* @return MorseNode - left
*/
public MorseNode getLeft() {
return left;
}
/**
* Sets left refrence
* @param left - refrence to the node to set
*/
public void setLeft(MorseNode left) {
this.left = left;
}
/**
* Gets the node refrenced by right
* @return MorseNode - right
*/
public MorseNode getRight() {
return right;
}
/**
* Sets right refrence
* @param right - refrence to the node to set
*/
public void setRight(MorseNode right) {
this.right = right;
}}
public class MorseMain {
public static void main(String[] args) {
//Do not modify this file.
MorseCoder mc = new MorseCoder();
mc.inOrderPrint();
// sos decode
System.out.println("Decode Test 1");
String str = "... --- ...";
System.out.println("str = " + str);
System.out.println("str should decode to: sos");
System.out.println("decode(str) = " + mc.decode(str));
testResults("sos", mc.decode(str));
// abcdef...xyz decode
System.out.println("Decode Test 2");
str = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -."
+ " --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..";
System.out.println("str = " + str);
System.out.println("str should decode to: abcdefghijklmnopqrstuvwxyz");
System.out.println("decode(str) = " + mc.decode(str));
testResults("abcdefghijklmnopqrstuvwxyz", mc.decode(str));
// helpmeobiwanyouremyonlyhope decode
System.out.println("Decode Test 3");
str = ".... . .-.. .--. -- . --- -... .. .-- .- -. -.-- --- ..-"
+ " .-. . -- -.-- --- -. .-.. -.-- .... --- .--. .";
System.out.println("str = " + str);
System.out.println("str should decode to: helpmeobiwanyouremyonlyhope");
System.out.println("decode(str) = " + mc.decode(str));
testResults("helpmeobiwanyouremyonlyhope", mc.decode(str));
// --.. encode
System.out.println("Encode Test 1");
str = "z";
System.out.println("str = " + str);
System.out.println("str should encode to: --..");
System.out.println("encode(str) = " + mc.encode(str));
testResults("--..", mc.encode(str));
// ... --- ... encode
System.out.println("Encode Test 2");
str = "sos";
System.out.println("str = " + str);
System.out.println("str should encode to: ... --- ...");
System.out.println("encode(str) = " + mc.encode(str));
testResults("... --- ...", mc.encode(str));
// .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -. encode
System.out.println("Encode Test 3");
str = "runforrestrun";
System.out.println("str = " + str);
System.out.println("str should encode to: .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.");
System.out.println("encode(str) = " + mc.encode(str));
testResults(".-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.", mc.encode(str));
}
/**
* Tests if the output string matches the expected.
* Prints "Test: Passed" if they match, otherwise prints "Test: Failed"
* @param one String - Expected output
* @param two String - Encoded/Decoded call
*/
public static void testResults(String one, String two) {
if(one.trim().equals(two.trim()))
System.out.println("Test: Passed");
else
System.out.println("Test: Failed");
System.out.println();
}
}
INPUT:
encodings.txt :
a .-
b -...
c -.-.
d -..
e .
f ..-.
g --.
h ....
i ..
j .---
k -.-
l .-..
m --
n -.
o ---
p .--.
q --.-
r .-.
s ...
t -
u ..-
v ...-
w .--
x -..-
y -.--
z --..
OUTPUT:
Sample output:
h
s
v
i
f
u
e
l
r
a
p
w
j
b
d
x
n
c
k
y
t
z
g
q
m
o
Decode Test 1
str = ... --- ...
str should decode to: sos
decode(str) = sos
Test: Passed
Decode Test 2
str = .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..
str should decode to: abcdefghijklmnopqrstuvwxyz
decode(str) = abcdefghijklmnopqrstuvwxyz
Test: Passed
Decode Test 3
str = .... . .-.. .--. -- . --- -... .. .-- .- -. -.-- --- ..- .-. . -- -.-- --- -. .-.. -.-- .... --- .--. .
str should decode to: helpmeobiwanyouremyonlyhope
decode(str) = helpmeobiwanyouremyonlyhope
Test: Passed
Encode Test 1
str = z
str should encode to: --..
encode(str) = --..
Test: Passed
Encode Test 2
str = sos
str should encode to: ... --- ...
encode(str) = ... --- ...
Test: Passed
Encode Test 3
str = runforrestrun
str should encode to: .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.
encode(str) = .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.
Test: Passed

More Related Content

PDF
In Java Write a program that reads an English language phrase and en.pdf
DOCX
Killian Vigna Morse code
KEY
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
PDF
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
DOCX
The assigment is overdue now. I will up the price I am willing to pa.docx
PDF
INSTRUCTIONS For this assignment you will be generating all code on y.pdf
PPT
Huffman > Data Structures & Algorithums
PDF
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
In Java Write a program that reads an English language phrase and en.pdf
Killian Vigna Morse code
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
The assigment is overdue now. I will up the price I am willing to pa.docx
INSTRUCTIONS For this assignment you will be generating all code on y.pdf
Huffman > Data Structures & Algorithums
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf

Similar to The Morse code (see Table 6.10 in book) is a common code that is use.pdf (20)

PPT
Data Structure and Algorithms Huffman Coding Algorithm
PDF
Data communication & computer networking: Huffman algorithm
PPTX
Turing Machine
PDF
I need help with the last 2 methods only in Huffman.java file the me.pdf
PDF
Data structuresUsing java language and develop a prot.pdf
DOC
DOCX
this is the code using array i want with stack or linked list  or .docx
PPTX
Huffman.pptx
PDF
expect("").length.toBe(1)
PDF
Music as data
PPT
String classes and its methods.20
PDF
Frequency .java Word frequency counter package frequ.pdf
PPTX
Text compression in LZW and Flate
PPT
PPT
PPT
Huffman 2
PDF
Sienna 12 huffman
PDF
Buacm 2
PPTX
Java string handling
PPS
String and string buffer
Data Structure and Algorithms Huffman Coding Algorithm
Data communication & computer networking: Huffman algorithm
Turing Machine
I need help with the last 2 methods only in Huffman.java file the me.pdf
Data structuresUsing java language and develop a prot.pdf
this is the code using array i want with stack or linked list  or .docx
Huffman.pptx
expect("").length.toBe(1)
Music as data
String classes and its methods.20
Frequency .java Word frequency counter package frequ.pdf
Text compression in LZW and Flate
Huffman 2
Sienna 12 huffman
Buacm 2
Java string handling
String and string buffer
Ad

More from bhim1213 (20)

PDF
In 1998, Congress passed legislation concerning shifting the burden .pdf
PDF
If A denotes some event, what does A denote If P(A)equals=0.997, wh.pdf
PDF
How do neutrophils find and get to an infectionSolutionNeutro.pdf
PDF
How many times will the following code print Welcome to Java in.pdf
PDF
From your own words not copy past from internet please Talked about.pdf
PDF
Forms an important part of the subunits of the ribosome. The _ are sp.pdf
PDF
During DNA replication, a series of steps are required to ensure tha.pdf
PDF
Disease X occurs when someone has the xx genotype. However, only 20 .pdf
PDF
Darwins Theory had five main tenets (or components), what are they.pdf
PDF
Define toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdf
PDF
A system was set up in parallel with two components, A and B. The pr.pdf
PDF
All content is made permanent for future use. All content will be lo.pdf
PDF
a. A waitress is serving 5 people at a table. She has the 5 dishes t.pdf
PDF
Biochemistry homework Focus concept ripening fruit and the activity.pdf
PDF
A process that has its representative PCB in a device queue is in th.pdf
PDF
Which of the following statements is (are) trueI Cash flow is a.pdf
PDF
What is the relationship of the epithelium of the epidermis to the co.pdf
PDF
What is a linked listWhat is a linked lists general syntaxCan .pdf
PDF
What is the output of running class GenericMethodDemo of the followi.pdf
PDF
What do you think are the roles of professional societies in contemp.pdf
In 1998, Congress passed legislation concerning shifting the burden .pdf
If A denotes some event, what does A denote If P(A)equals=0.997, wh.pdf
How do neutrophils find and get to an infectionSolutionNeutro.pdf
How many times will the following code print Welcome to Java in.pdf
From your own words not copy past from internet please Talked about.pdf
Forms an important part of the subunits of the ribosome. The _ are sp.pdf
During DNA replication, a series of steps are required to ensure tha.pdf
Disease X occurs when someone has the xx genotype. However, only 20 .pdf
Darwins Theory had five main tenets (or components), what are they.pdf
Define toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdf
A system was set up in parallel with two components, A and B. The pr.pdf
All content is made permanent for future use. All content will be lo.pdf
a. A waitress is serving 5 people at a table. She has the 5 dishes t.pdf
Biochemistry homework Focus concept ripening fruit and the activity.pdf
A process that has its representative PCB in a device queue is in th.pdf
Which of the following statements is (are) trueI Cash flow is a.pdf
What is the relationship of the epithelium of the epidermis to the co.pdf
What is a linked listWhat is a linked lists general syntaxCan .pdf
What is the output of running class GenericMethodDemo of the followi.pdf
What do you think are the roles of professional societies in contemp.pdf
Ad

Recently uploaded (20)

PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Pharma ospi slides which help in ospi learning
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Institutional Correction lecture only . . .
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Cell Types and Its function , kingdom of life
PPTX
master seminar digital applications in india
human mycosis Human fungal infections are called human mycosis..pptx
Pharma ospi slides which help in ospi learning
Supply Chain Operations Speaking Notes -ICLT Program
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
GDM (1) (1).pptx small presentation for students
Microbial diseases, their pathogenesis and prophylaxis
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Structure & Organelles in detailed.
TR - Agricultural Crops Production NC III.pdf
Basic Mud Logging Guide for educational purpose
102 student loan defaulters named and shamed – Is someone you know on the list?
Final Presentation General Medicine 03-08-2024.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Institutional Correction lecture only . . .
Microbial disease of the cardiovascular and lymphatic systems
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Cell Types and Its function , kingdom of life
master seminar digital applications in india

The Morse code (see Table 6.10 in book) is a common code that is use.pdf

  • 1. The Morse code (see Table 6.10 in book) is a common code that is used to encode messages consisted of letters and digits. Each letter consists of a series of dots and dashes; for example, the code for the letter a is *- and the code for the letter b is -***. Store each letter of the alphabet in a node of a binary tree of level 5. The root node is at level 1 and stores no letter. The left node at level 2 stores the letter e (code is *), and the right node stores letter t (code is -). The 4 nodes at level 3 store the letters with codes (**, *-, -*, --). To build the tree (see Figure 6.38 in book), read a file in which each line consists of a letter followed by its code. The letters should be ordered by tree level. To find the position for a letter in the tree, scan the code and branch left for a dot and branch right for a dash. Encode a message by replacing each letter by its code symbol. Then decode the message using the Morse code tree. Make sure you use a delimiter symbol between coded letters. Implementation Notes: You will need to complete the generic implementation of the BinaryTree data structure first (see slides). Once it is complete, solve the problem above (note that the book uses dots and dashes, we will use the asterisk (*) as the dot, hyphen (-) as a dash, and space ( ) as the delimiter symbol between coded letters). Provide a menu program that asks the user to 1) test output for all morse code letters with their respective translated alphabet letters (make sure you are using the binary tree to do the actual translation, output as a nicely formatted table), 2) enter an input file name to decode morse code and output the translated text to the screen, or 3) enter in a line of morse code through the console to decode morse code and output the translated text to the screen relevenat picture of both the tree diagram and the table of morse code Solution JAVA CODE: import java.io.*; import java.util.*; public class MorseCoder implements MorseCodeInterface { private MorseNode root; /** * constructor to build the tree */ public MorseCoder() { root = new MorseNode();
  • 2. readTreeInfo(); } /** * reads in the tree info from the text file (helper method) */ private void readTreeInfo() { Scanner input = null; try { input = new Scanner(new File("encodings.txt")); } catch (FileNotFoundException exception) { System.out.println("File not found!"); } while (input.hasNextLine()) { String data = input.nextLine().trim(); if (data.length() > 0) { add(data.substring(1).trim(), data.charAt(0)); } } input.close(); } /** * adds the letter to the tree based on the mcode string (helper method) * @param mcode the string being fed in * @param ltr the letter being added at the node */ private void add(String mcode, char ltr) { MorseNode current = root; String signal = " "; for (int i = 0; i < mcode.length(); i++) { signal = mcode.substring(i, i + 1); if (signal.equals(".")) { if (current.getLeft() != null) { current = current.getLeft(); } else { current.setLeft(new MorseNode()); current = current.getLeft();
  • 3. } } else { if (current.getRight() != null) { current = current.getRight(); } else { current.setRight(new MorseNode()); current = current.getRight(); } } } current.setLetter(ltr); } /** * prints out inorder tree contents */ public void inOrderPrint() { MorseNode current = root; printInorder(current); } /** * called by inOrderPrint to print tree contents (helper method) * @param current the node to print */ private void printInorder(MorseNode current) { if (current != null) { printInorder(current.getLeft()); System.out.print(current.getLetter()); printInorder(current.getRight()); } } /** * decodes a String of morse code to English * @param str String of morse code * @return result String of English */ public String decode(String str) {
  • 4. String signal = ""; StringBuffer result = new StringBuffer(""); MorseNode current = root; for (int i = 0; i < str.length(); i++) { signal = str.substring(i, i + 1); if (signal.equals(".")) { if (current.getLeft() != null) { current = current.getLeft(); } else { current.setLeft(new MorseNode()); current = current.getLeft(); } } else if (signal.equals("-")) { if (current.getRight() != null) { current = current.getRight(); } else { current.setRight(new MorseNode()); current = current.getRight(); } } else { result = result.append(current.getLetter()); current = root; } } result = result.append(current.getLetter()); return result.toString(); } /** * decodes a String of English to morse code * @param str String of English * @return result String of morse code */ public String encode(String str) { MorseNode current = root; String result = "";
  • 5. String s = ""; char ltr; for (int i = 0; i < str.length(); i++) { ltr = str.charAt(i); result = searchTree(current, ltr, s); } return result; } /** * searches the tree for the letter(s) being inputed and outputs a string of morse (helper method) * @param current the node of the tree * @param ltr the letter being searched for in the tree * @param s the String being used to build the morse code * @return the morse code corresponding to the item being checked */ public String searchTree(MorseNode current, char ltr, String s) { char temp = current.getLetter(); //for debugging purposes if (current.getLetter() == ltr) { return s; } else { if (current.getLeft() != null) { return searchTree(current.getLeft(), ltr, s + "."); } if (current.getRight() != null) { return searchTree(current.getRight(), ltr, s + "-"); } return s; } } } /*Interface*/ public interface MorseCodeInterface { void inOrderPrint(); String decode(String str);
  • 6. String encode(String str); } /** * Node class to use with morsecode tree. Do not modify this class. */ public class MorseNode { /** a letter of the alphabet */ private char letter; /** reference to the left child */ private MorseNode left; /** reference to the right child */ private MorseNode right; /** value of letter if empty (not set) */ public static final char EMPTY = ' '; /*** Default constructor, actual values are set in the MorseCode constructor*/ public MorseNode() { letter = EMPTY; left = null; right = null; } /** * Gets letter contained in node * @return String - letter value */ public char getLetter() { return letter; } /** * Sets letter in node * @param String - letter to set */ public void setLetter(char letter) { this.letter = letter; } /** * Gets the node refrenced by left
  • 7. * @return MorseNode - left */ public MorseNode getLeft() { return left; } /** * Sets left refrence * @param left - refrence to the node to set */ public void setLeft(MorseNode left) { this.left = left; } /** * Gets the node refrenced by right * @return MorseNode - right */ public MorseNode getRight() { return right; } /** * Sets right refrence * @param right - refrence to the node to set */ public void setRight(MorseNode right) { this.right = right; }} public class MorseMain { public static void main(String[] args) { //Do not modify this file. MorseCoder mc = new MorseCoder(); mc.inOrderPrint(); // sos decode System.out.println("Decode Test 1"); String str = "... --- ..."; System.out.println("str = " + str); System.out.println("str should decode to: sos");
  • 8. System.out.println("decode(str) = " + mc.decode(str)); testResults("sos", mc.decode(str)); // abcdef...xyz decode System.out.println("Decode Test 2"); str = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -." + " --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.."; System.out.println("str = " + str); System.out.println("str should decode to: abcdefghijklmnopqrstuvwxyz"); System.out.println("decode(str) = " + mc.decode(str)); testResults("abcdefghijklmnopqrstuvwxyz", mc.decode(str)); // helpmeobiwanyouremyonlyhope decode System.out.println("Decode Test 3"); str = ".... . .-.. .--. -- . --- -... .. .-- .- -. -.-- --- ..-" + " .-. . -- -.-- --- -. .-.. -.-- .... --- .--. ."; System.out.println("str = " + str); System.out.println("str should decode to: helpmeobiwanyouremyonlyhope"); System.out.println("decode(str) = " + mc.decode(str)); testResults("helpmeobiwanyouremyonlyhope", mc.decode(str)); // --.. encode System.out.println("Encode Test 1"); str = "z"; System.out.println("str = " + str); System.out.println("str should encode to: --.."); System.out.println("encode(str) = " + mc.encode(str)); testResults("--..", mc.encode(str)); // ... --- ... encode System.out.println("Encode Test 2"); str = "sos"; System.out.println("str = " + str); System.out.println("str should encode to: ... --- ..."); System.out.println("encode(str) = " + mc.encode(str)); testResults("... --- ...", mc.encode(str));
  • 9. // .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -. encode System.out.println("Encode Test 3"); str = "runforrestrun"; System.out.println("str = " + str); System.out.println("str should encode to: .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -."); System.out.println("encode(str) = " + mc.encode(str)); testResults(".-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.", mc.encode(str)); } /** * Tests if the output string matches the expected. * Prints "Test: Passed" if they match, otherwise prints "Test: Failed" * @param one String - Expected output * @param two String - Encoded/Decoded call */ public static void testResults(String one, String two) { if(one.trim().equals(two.trim())) System.out.println("Test: Passed"); else System.out.println("Test: Failed"); System.out.println(); } } INPUT: encodings.txt : a .- b -... c -.-. d -.. e . f ..-. g --. h .... i ..
  • 10. j .--- k -.- l .-.. m -- n -. o --- p .--. q --.- r .-. s ... t - u ..- v ...- w .-- x -..- y -.-- z --.. OUTPUT: Sample output: h s v i f u e l r a p w j b
  • 11. d x n c k y t z g q m o Decode Test 1 str = ... --- ... str should decode to: sos decode(str) = sos Test: Passed Decode Test 2 str = .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. str should decode to: abcdefghijklmnopqrstuvwxyz decode(str) = abcdefghijklmnopqrstuvwxyz Test: Passed Decode Test 3 str = .... . .-.. .--. -- . --- -... .. .-- .- -. -.-- --- ..- .-. . -- -.-- --- -. .-.. -.-- .... --- .--. . str should decode to: helpmeobiwanyouremyonlyhope decode(str) = helpmeobiwanyouremyonlyhope Test: Passed Encode Test 1 str = z str should encode to: --.. encode(str) = --.. Test: Passed Encode Test 2 str = sos
  • 12. str should encode to: ... --- ... encode(str) = ... --- ... Test: Passed Encode Test 3 str = runforrestrun str should encode to: .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -. encode(str) = .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -. Test: Passed /** * Node class to use with morsecode tree. Do not modify this class. */ public class MorseNode { /** a letter of the alphabet */ private char letter; /** reference to the left child */ private MorseNode left; /** reference to the right child */ private MorseNode right; /** value of letter if empty (not set) */ public static final char EMPTY = ' '; /*** Default constructor, actual values are set in the MorseCode constructor*/ public MorseNode() { letter = EMPTY; left = null; right = null; } /** * Gets letter contained in node * @return String - letter value */ public char getLetter() { return letter; } /** * Sets letter in node * @param String - letter to set
  • 13. */ public void setLetter(char letter) { this.letter = letter; } /** * Gets the node refrenced by left * @return MorseNode - left */ public MorseNode getLeft() { return left; } /** * Sets left refrence * @param left - refrence to the node to set */ public void setLeft(MorseNode left) { this.left = left; } /** * Gets the node refrenced by right * @return MorseNode - right */ public MorseNode getRight() { return right; } /** * Sets right refrence * @param right - refrence to the node to set */ public void setRight(MorseNode right) { this.right = right; }} public class MorseMain { public static void main(String[] args) { //Do not modify this file. MorseCoder mc = new MorseCoder();
  • 14. mc.inOrderPrint(); // sos decode System.out.println("Decode Test 1"); String str = "... --- ..."; System.out.println("str = " + str); System.out.println("str should decode to: sos"); System.out.println("decode(str) = " + mc.decode(str)); testResults("sos", mc.decode(str)); // abcdef...xyz decode System.out.println("Decode Test 2"); str = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -." + " --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.."; System.out.println("str = " + str); System.out.println("str should decode to: abcdefghijklmnopqrstuvwxyz"); System.out.println("decode(str) = " + mc.decode(str)); testResults("abcdefghijklmnopqrstuvwxyz", mc.decode(str)); // helpmeobiwanyouremyonlyhope decode System.out.println("Decode Test 3"); str = ".... . .-.. .--. -- . --- -... .. .-- .- -. -.-- --- ..-" + " .-. . -- -.-- --- -. .-.. -.-- .... --- .--. ."; System.out.println("str = " + str); System.out.println("str should decode to: helpmeobiwanyouremyonlyhope"); System.out.println("decode(str) = " + mc.decode(str)); testResults("helpmeobiwanyouremyonlyhope", mc.decode(str)); // --.. encode System.out.println("Encode Test 1"); str = "z"; System.out.println("str = " + str); System.out.println("str should encode to: --.."); System.out.println("encode(str) = " + mc.encode(str)); testResults("--..", mc.encode(str)); // ... --- ... encode
  • 15. System.out.println("Encode Test 2"); str = "sos"; System.out.println("str = " + str); System.out.println("str should encode to: ... --- ..."); System.out.println("encode(str) = " + mc.encode(str)); testResults("... --- ...", mc.encode(str)); // .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -. encode System.out.println("Encode Test 3"); str = "runforrestrun"; System.out.println("str = " + str); System.out.println("str should encode to: .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -."); System.out.println("encode(str) = " + mc.encode(str)); testResults(".-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -.", mc.encode(str)); } /** * Tests if the output string matches the expected. * Prints "Test: Passed" if they match, otherwise prints "Test: Failed" * @param one String - Expected output * @param two String - Encoded/Decoded call */ public static void testResults(String one, String two) { if(one.trim().equals(two.trim())) System.out.println("Test: Passed"); else System.out.println("Test: Failed"); System.out.println(); } } INPUT: encodings.txt : a .- b -... c -.-.
  • 16. d -.. e . f ..-. g --. h .... i .. j .--- k -.- l .-.. m -- n -. o --- p .--. q --.- r .-. s ... t - u ..- v ...- w .-- x -..- y -.-- z --.. OUTPUT: Sample output: h s v i f u e l r
  • 17. a p w j b d x n c k y t z g q m o Decode Test 1 str = ... --- ... str should decode to: sos decode(str) = sos Test: Passed Decode Test 2 str = .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. str should decode to: abcdefghijklmnopqrstuvwxyz decode(str) = abcdefghijklmnopqrstuvwxyz Test: Passed Decode Test 3 str = .... . .-.. .--. -- . --- -... .. .-- .- -. -.-- --- ..- .-. . -- -.-- --- -. .-.. -.-- .... --- .--. . str should decode to: helpmeobiwanyouremyonlyhope decode(str) = helpmeobiwanyouremyonlyhope Test: Passed Encode Test 1
  • 18. str = z str should encode to: --.. encode(str) = --.. Test: Passed Encode Test 2 str = sos str should encode to: ... --- ... encode(str) = ... --- ... Test: Passed Encode Test 3 str = runforrestrun str should encode to: .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -. encode(str) = .-. ..- -. ..-. --- .-. .-. . ... - .-. ..- -. Test: Passed