Paige An wrote:I'm having some trouble with getting this program to read an input of morse code and then produce an output of English. When typing in morse code for the phrase 'the string', the output looks something like this:
...
Any help would be greatly appreciated.
OK, well clearly your program isn't processing the "last letter" it receives; and the reason is that
while(morseWord.indexOf(" ") > 0) { ...
test.
As soon as it returns false, you simply drop out of the loop, when in fact you almost certainly have another letter to process.
One possibility would be to make that loop a
do...while loop; but even easier is probably to use
String.split(). It was created for
precisely the kind of processing you're doing, and you could use it for both "words" and "letters".
Another point: You have - quite rightly - split out your translation to Morse into a separate method, but you still have all your "translate to English" code in
main(). Why? If you had a
toEnglish() method, your
main() could be as simple as:
You may also notice that I use the first input to create a
boolean. It's not required, but I think you'll agree that it makes the code more readable. Why? Because Strings should ONLY be used to contain text; and in this case your '
answer' field is redundant because it simply contains the answer to the question "Do you want to translate to Morse?". For more info, have a look at the
StringsAreBad page.
Also:
1. You don't have to create a NEW Scanner every time you get new input. The 'scan' creation at line 31 is therefore redundant.
2. What do you do if the user enters something invalid? Right now, it looks like you'll just end up spitting out blanks, which isn't very helpful. Good programmers have a strategy for what to do when things go
wrong.
HIH
Winston
PS: I've broken up your lines as best I can because they are
FAR TOO LONG (mostly because your indenting is excessive). Please read the link before you post any more code. Thanks.