Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Name: T. Nguyen
- * Date: Jan. 26th, 2021
- * Last updated: Jan. 26th, 2021
- * Description: This class file contains the decoding/encoding methods to convert lines of Morse code to words, or vice versa.
- */
- public class MorseCode
- {
- public static void main(String[] args)
- {
- String[] text = {"* * * * * * _ _ * _ * . _ * * .", "_ * _ _ _ _ _ * * _ _ _ * _ _ _
- _ _ _ _ * * ?",
- "* * * _ * * * * _ * _ * _ * * * * * * * * * ."};
- text = morseDecrypt(text);
- for (int i = 0; i < text.length; i++)
- {
- System.out.println(text[i]);
- }
- }//End main
- public static String[] morseDecrypt(String[] textArray)
- {
- //Declarations & Initializations
- String[] decrypted = new String[textArray.length];
- int morseCount = 0;
- for (int i = 0; i < textArray.length; i++)
- {
- textArray[i] = textArray[i].replaceAll(" ", "#%");
- textArray[i] = textArray[i].replaceAll(" ", "#");
- System.out.println(textArray[i]);
- decrypted[i] += morseLetDecrypt(textArray[i]);
- }
- return decrypted;
- }//End morseDecrypt()
- public static String morseLetDecrypt(String morseLine)
- {
- final String[] morseCodes = {"* _", "_ * * *", "_ * _ *", "_ * *", "*", "* * _ *", "_ _ *", "* * * *", "* *", "* _ _ _", "_ *
- _", "* _ * *", "_ _",
- "_ *", "_ _ _", "* _ _ *", "_ _ * _", "* _ *", "* * *", "_", "* * _", "* * * _", "*_ _", "_ * * _",
- "_ * _ _", "_ _ * *"};
- final char[] alphabet = {'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'};
- String morseLetter = "";
- int morseCount = 0;
- //Base Cases
- if (morseLine.length() == 0)
- {
- return morseLine;
- }
- //Recursive Code
- if (morseLine.charAt(0) != '*' && morseLine.charAt(0) != '_' && morseLine.charAt(0) != ' ' && morseLine.charAt(0) != '#')
- {
- if (morseLine.charAt(0) == '%')
- {
- return " " + morseLetDecrypt(morseLine.substring(1));
- }
- else
- {
- return morseLine.charAt(0) + morseLetDecrypt(morseLine.substring(1));
- }
- }
- for (int i = 0; i < morseLine.length(); i++)
- {
- if (morseLine.charAt(i) == '*' || morseLine.charAt(i) == '_' || morseLine.charAt(i) == ' ')
- {
- morseCount++;
- morseLetter += morseLine.charAt(i);
- }
- else
- {
- break;
- }
- }
- for (int i = 0; i < morseCodes.length; i++)
- {
- if (morseLetter.equals(morseCodes[i]))
- {
- return alphabet[i] + morseLetDecrypt(morseLine.substring(morseCount + 1));
- }
- }
- return morseLetter + morseLetDecrypt(morseLine.substring(morseCount + 1));
- }
- }//End class
Add Comment
Please, Sign In to add comment