Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.Arrays;
- public class test {
- public static void main( String [] args )
- {
- Scanner input = new Scanner(System.in);
- String [] alpha = {"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","1","2","3","4","5","6","7","8","9","0"," "};
- String [] dottie = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----", "|"};
- System.out.println("Enter English to convert to English or Morse to convert to Morse:");
- String ans = input.nextLine();
- if(ans.equals("English"))
- {
- System.out.println( "Please enter the text you would like to convert to Morse Code: ");
- String english = input.nextLine();
- char [] translates = (english.toLowerCase()).toCharArray();
- System.out.println(toMorse(translates, dottie));
- }
- else if(ans.equals("Morse"))
- {
- System.out.println( "Please enter the text you would like to convert to English (separate words with '|'):");
- String code = input.nextLine();
- String[] translates = code.split("[|]", 0);
- System.out.println(toEnglish(translates, dottie, alpha));
- }
- else
- System.out.println("Invalid input, please try again.");
- }
- public static String toMorse(char [] translates, String [] dottie)
- {
- String morse = "";
- for (int j = 0; j < translates.length; j++)
- {
- char a = translates[j]; //.valueOf(j);
- if(Character.isLetter(a))
- {
- morse += dottie[a - 'a'];
- }
- }
- return morse;
- }
- // the current solution won't need alpha; but the other one (commented out), need it
- // for the sake of Something, I have kept the signature with 3 args.
- // uncomment the s+=alpha[k] line, comment the s+=Character... line and you should
- // have the solution using the alpha array to convert back. See explanation in the answer.
- public static String toEnglish(String [] translates, String [] dottie, String[] alpha)
- {
- String s = "";
- for (int n = 0; n < translates.length; n++)
- {
- String a = translates[n];
- int k = Arrays.asList(dottie).indexOf(a);
- if (k >= 0) {
- //s += alpha[k];
- s += Character.toChars(k + 'a')[0];
- }
- }
- return s;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement