Need assistance with java morse code translator only translating one symbol -
i made java morse code translator when convert morse english converts each symbol letter when translate .... gives me e e e e instead of h. question how make can translate whole words in morse code , use | separate words.
here code
public class project1 { public static void main ( string [] args ) { char [] english = { '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 [] morse = { ".-" , "-..." , "-.-." , "-.." , "." , "..-." , "--." , "...." , ".." , ".---" , "-.-" , ".-.." , "--" , "-." , "---" , ".--." , "--.-" , ".-." , "..." , "-" , "..-" , "...-" , ".--" , "-..-" , "-.--" , "--.." , "|" }; string = input.getstring ( "please enter mc if want translate morse code english, or eng if want translate english morse code" ); if (a.equals("mc")) { string b = input.getstring ("please enter sentence in morse code. separate each letter/digit single space , delimit multiple words | ."); string[] words = b.split("|"); (string word: words ) { string[] characters = word.split(" "); (string character: characters) { if (character.isempty()) { continue; } (int m = 0; m < morse.length; m++) { if (character.equals(morse[m])) system.out.print(english[m]); } } system.out.print(" "); } } else if (a.equals("eng")) { string c = input.getstring ( "please enter sentence in english, , separate each word blank space." ); c = c.tolowercase (); ( int x = 0; x < english.length; x++ ) { ( int y = 0; y < c.length (); y++ ) { if ( english [ x ] == c.charat ( y ) ) system.out.print ( morse [ x ] + " " ); } } } else { system.out.println ( "invalid input" ); } } }
a problem you're having string#split(...) method not taking account | special character regard regular expressions , not splitting string expect. need escape character things work right. change this:
string[] words = b.split("|"); to this:
string[] words = b.split("\\|"); // escaping pipe char to debug , see if things working expected, use debugger or sprinkle println's in code like:
string[] words = b.split("\\|"); // todo: remove line below finished program system.out.println(java.util.arrays.tostring(words)); as aside, if program, i'd use hashmap<string, string> assist translation of english morse , visa-versa.
on further searching performed, please check out: why string.split need pipe delimiter escaped? background information on why pipe char needs escaped.
Comments
Post a Comment