Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

10-16. Write a program that ask the user to enter a string, and then converts th

ID: 3620377 • Letter: 1

Question

10-16.
Write a program that ask the user to enter a string, and then converts that string to Morse code. Morse code is provided. I have already put it in the program. Here is my program. Please make this one work. I have an errors and cant get it to compile. I use JCreator.

import javax.swing.JOptionPane;
/**
* @(#)MorseCode.java
*
*
* @author
* @version 1.00 2010/9/27
*/

public class MorseCode
{



public static void main(String[] args)
{

String input;
String sentence;
input = JOptionPane.showInputDialog("Enter a string and I will " +
"convert it to morse code");

morseCodeSentence(input);
System.exit(0);
}

public static void morseCodeSentence(String mc)
{
char[] array;
array = mc.toCharArray();

char[] letters = { ' ', ',', '.', '?', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '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[] morseCode = {" ", "--..--",".-.-.-", "..--..", "-----", ".----",
"..---", "...--", "....-", ".....", "-....",
"--...", "---..", "----.", ".-", "-...", ".-.-",
"-..", ".", "..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-",
"-.--", "--.." };

StringBuilder str = new StringBuilder();

for (int index = 0; index < array.length; index++)
{
for (int count = 0; count < letters.length; count++)
{


if(Character.toUpperCase(array[index]) == letters[index])
{
array[index] = morseCode[count];
}

}

}

//append
for (int loop = 0; loop < array.length; loop++)
{
str.append(array[loop]);
}

JOptionPane.showMessageDialog(null, mc + "is" + str);





}
}

Explanation / Answer

I think you were on the right track with the nested for loops but your if statement should look more like if(Character.toUpperCase(array[index]) == letters[count]) that way each character gets compared to each character in the letters array then inside this if statement is where you should use the append method. Assuming the letters array and the morseCode arrays equivalents match up number wise you can just put: str.append(morseCode[count]); because count will be the correct location in letters. Then you shouldnt need that last for loop you have there and it should print out the correct morse code.