-3

This Java code should prompt the user to choose between Morse code and English, then prompt them to enter a string in the language they chose. It should then produce a translation to the other language. It compiles on my machine, though it sometimes doesn't work correctly.

Can someone else try and run it for me and just tell me if it works? If not, can you point me to the error in my code that is producing the runtime error?

public class MorseCodeJavaProgram 
{
    public static void morse( String s3 )
    {
        int letters [ ] = new int [ 26 ];

        for ( int num = 0; num < s3.length(); num++ )
        {
            switch ( s3.charAt( num ) )
            {
                case 'a':
                    System.out.print( ".- ");
                    break;
                case 'b':
                    System.out.print( "-… ");
                    break;
                case 'c':
                    System.out.print( "-.-. ");
                    break;
                case 'd':
                    System.out.print( "-.. ");
                    break;
                case 'e':
                    System.out.print( ". ");
                    break;
                case 'f':
                    System.out.print( "..-. ");
                    break;
                case 'g':
                    System.out.print( "--. ");
                    break;
                case 'h':
                    System.out.print( "…. ");
                    break;
                case 'i':
                    System.out.print( ".. ");
                    break;
                case 'j':
                    System.out.print( ".--- ");
                    break;
                case 'k':
                    System.out.print( "-.- ");
                    break;
                case 'l':
                    System.out.print( ".-.. ");
                    break;
                case 'm':
                    System.out.print( "-- ");
                    break;
                case 'n':
                    System.out.print( "-. ");
                    break;
                case 'o':
                    System.out.print( "--- ");
                    break;
                case 'p':
                    System.out.print( ".--. ");
                    break;
                case 'q':
                    System.out.print( "--.- ");
                    break;  
                case 'r':
                    System.out.print( ".-. ");
                    break;  
                case 's':
                    System.out.print( "... ");
                    break;
                case 't':
                    System.out.print( "- ");
                    break;  
                case 'u':
                    System.out.print( "..- ");
                    break;  
                case 'v':
                    System.out.print( "...- ");
                    break;
                case 'w':
                    System.out.print( ".-- ");
                    break;
                case 'x':
                    System.out.print( "-..- ");
                    break;
                case 'y':
                    System.out.print( "-.-- ");
                    break;
                case 'z':
                    System.out.print( "--.. ");
                    break;
                case ' ':
                    System.out.print( " | ");
                    break;
            }

        }
    }

    public static void toEnglish( String s1 )
    {
        String english [ ] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "x", "y", "z", " " };
        String morse [ ] = { ".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. ", "--. ", "…. ", ".. ", ".--- ", "-.- ", ".-.. ", "-- ", "-. ", "--- ", ".--. ", "--.- ", ".-. ", "... ", "- ", "..- ", "...- ", ".-- ", "-..- ", "-.-- ", "--.. ", "| " };

        for ( int num = 0; num < s1.length(); num++ )
        {
            if ( s1.charAt ( num ) == ' ')
            {
                for ( int num2 = num; num2 < s1.length(); num2++ )
                {
                    if ( s1.charAt ( num2++ ) == ' ')
                    {
                        for ( int num3 = 0; num < 26; num3++ )
                        {
                            if ( s1.substring( num++, num2 + 2 ) == ( morse [ num3 ] ))
                            {
                                System.out.print( english [ num3 ] );
                            }
                        }
                    }

                }


            }
        }
    }

    public static void main( String [] args)
    {
        System.out.println("Begin Program");

        String s2 = Input.getString( "To Morse or From Morse" );
        if ("From Morse".equals(s2)  ){
            String s1 = Input.getString( "Please type a phrase in English" );
            toEnglish( " " + s1 + " " );
        }

        if ("To Morse".equals(s2) )
        {
            String s3 = Input.getString( "Please type a phrase in Morse Code" );
            morse( s3 );
        }
    }
}

When I get an error it states "Check console for possible error message, unable to be launched."

Below I added the Input.java file to be compiled to Input.class

import javax.swing.*;


public class Input
{
    public static byte getByte( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return Byte.parseByte( input );
    }

    public static short getShort( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return Short.parseShort( input );
    }

    public static int getInt( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return Integer.parseInt( input );
    }

    public static long getLong( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return Long.parseLong( input );
    }

    public static float getFloat( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return Float.parseFloat( input );
    }

    public static double getDouble( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return Double.parseDouble( input );
    }

    public static boolean getBoolean( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return Boolean.parseBoolean( input );
    }

    public static char getChar( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return input.charAt(0);
    }

    public static String getString( String s )
    {
        String input = JOptionPane.showInputDialog( s );
        return input;
    }

}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Skier1999
  • 15
  • 1
  • 6
  • Add the error you get to your question – HDJEMAI Jan 02 '16 at 21:00
  • @HocineDJEMAI I just edited question to include error message – Skier1999 Jan 02 '16 at 21:02
  • @Rakim above is the Input.Class andy thoughts you might have could really help me. – Skier1999 Jan 02 '16 at 21:33
  • "**Check console for possible error message, unable to be launched.**" is not the error message itself. To expect an answer you have to do a minimum effort – HDJEMAI Jan 02 '16 at 22:01
  • @HocineDJEMAI I have compiled and run the program. It runs. I type in all the information but instead of printing anything I get that pop up error message (a yellow triangle with a ! and the java coffee cup on it) This is exactly why I am confused. I have never seen this before and am new to coding. Please help me. I don't know what else to say because after researching I don't understand the error so I am trying to ask others who might. – Skier1999 Jan 02 '16 at 22:07
  • The class name Input may be a keyword for some other class, perhaps something using the Scanner class. Try changing the Input class name to UserInput and see if that helps. I don't have any problems with the code other than some minor issues. – DevilsHnd - 退職した Jan 02 '16 at 22:13
  • Thank you so much. This helped me understand a lot more about the way to properly write my code. Thank you very much for all the help with this. Is there a way I can send you a direct message about another program with the same message? Once again you have been very helpful and encouraging for me and my coding. @DevilsHnd – Skier1999 – Skier1999 Jan 04 '16 at 20:01

1 Answers1

0

Well....When I test the code it does in fact contain an error within the toEnglish() method when trying to translate Morse code to English but, it's definitely not the error you are getting and I obviously only get the exception when trying to translate Morse Code to English.

I get a StringIndexOutOfBoundsException exception and the line throwing the exception is:

if ( s1.substring( num++, num2 + 2 ) == ( morse [ num3 ] ))

For starters you are missing a element within your english[] String Array. Notice that you are missing the "w" within that array. With one element missing you now have a index miss-match between the english[] Array and the morse[] array. We need to make sure that the "w" is contained within the english[] string array otherwise when a 'w' is encountered the code won't be able to translate it.

Another thing, if at all possible, try to avoid using == (double equals) within your conditional statements when comparing strings. Get into the train of thought for using the String.equals() method instead, like this:

if (s1.substring(num++, num2 + 2).equals(morse[num3]))

More than a fair share of coding errors are due to a missed equals character even though compiling is fine. There are other issues with using == and they best covered here:

Not that this fixes your error within the toEnglish() method code block mind you. To be honest, this code gives me a headache just to look at it let alone sort through the logic of it. No disrespect intended here @Skier1999, it's a darn good attempt. Your problem with this code is that you're incrementing your indexing within both your for/loops and conditional if statements and this is throwing your indexing out of wack and then eventually....the StringIndexOutOfBounds Exception.

Rather than repairing this logic within the toEnglish() method, which can be done with a little tweaking, I would like to actually propose a different method of doing this translation. Well, both translations actually. Let's start with the two String Arrays, english[] and morse[]. How about we scrap those and create one two dimensional array which will contain both the alphanumeric characters and their related Morse Code equivalent. A sort of translation table so to speak. Then let's place this 2D Array (named morseEnglish) under the class constructor so that it's accessible by all methods within the class. Here is the array I propose:

static String[][] morseEnglish = {{"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","--.."}, {" ","|"}, {".",".-.-.-"}, {",","--..--"},
        {":","---..."}, {"?","..--.."}, {"'",".----."}, {"-", "-....-"}, {"/","-..-."}, 
        {"\"",".-..-."}, {"@",".--.-."}, {"=","-...-"}, {"(","-.--.-"}, {")","-.--.-"}, 
        {"0","-----"}, {"1",".----"}, {"2","..---"}, {"3","...--"}, {"4","....-"}, {"5","....."},
        {"6","-...."}, {"7","--..."}, {"8","---.."}, {"9","----."}};

This array also covers numbers and puctuation to Morse.

Now let's start with the toMorse() method. Lets get rid of that long switch/case thingy goin on and just use a couple for/loops instead. Let's just forget about skipping through each character of the input text string with the charAt() method and instead use the String.substring() method. We'll then iterate through our morseEnglish 2D Array and see if we can get a match for each character and when we do the related Morse element to that character is appended to a string conveniently named translation. Here is what the toMorse() method would look like:

public static void toMorse(String s3) {
    String translation = "";
    for ( int i = 0; i < s3.length(); i++ ) {
        String c = s3.substring(i, i+1);
        for (int j = 0; j < morseEnglish.length; j++){
            if (morseEnglish[j][0].equals(c)) {
                if (translation.equals("")) { translation = morseEnglish[j][1]; }
                else { translation+= " " + morseEnglish[j][1]; }
            }
        }
    }

    System.out.println("Morse Code:  " + translation);
    JOptionPane.showMessageDialog(null, translation, "English To Morse Code", JOptionPane.INFORMATION_MESSAGE);
}

There...that should cover Text String to Morse Code translation (conversion). Now let's deal with the toEnglish() method which was causing an exception anyways. Because we have our 2D Array translation table, we can basically do the same thing to convert a Morse Code string to English (Alphanumeric) text. We just use a different index in our morseEnglish 2D Array on a successful comparison to get the related Alphanumeric to Morse data. Because each Morse Code character sequence is separated by a whitespace we can use the String.split() method to place the entire Morse Code string into yet another String Array named code[] (no charAt() method here). This way we can simply iterate through the new code[] array, get the full Morse character representation and compare it to our 2D translation table array (morseEnglish[][]) then pull out the related character element. Here is the proposed toEnglish() method:

public static void toEnglish(String s1) {
    String code[] = s1.split(" ");
    String translation = "";
    for (int i = 0; i < code.length; i++) {
        for (int j = 0; j < morseEnglish.length; j++){
            if (morseEnglish[j][1].equals(code[i])) {
                translation+= morseEnglish[j][0];
            }
        }
    }

    System.out.println("English:  " + translation);
    JOptionPane.showMessageDialog(null, translation, "Morse Code To English", JOptionPane.INFORMATION_MESSAGE);
}

This is much easier to follow and more efficient in my opinion. There are other ways of doing this sort of thing like using Map but I think for now this is the easiest for you to grasp at this point.

I have tweaked a few other things in your code as well. The Input Class seems to work fine but is somewhat overkill for what you are currently doing with this bit of code not to mention that the class is relatively limited as to what the JOptionPane.showInputDialog() can truly do but what the heck...it's functional. Here is the entire MorseCodeJavaProgram Class:

package morsecodejavaprogram;

import javax.swing.JOptionPane;

public class MorseCodeJavaProgram {
    static String[][] morseEnglish = {{"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","--.."}, {" ","|"}, {".",".-.-.-"}, {",","--..--"},
            {":","---..."}, {"?","..--.."}, {"'",".----."}, {"-", "-....-"}, {"/","-..-."}, 
            {"\"",".-..-."}, {"@",".--.-."}, {"=","-...-"}, {"(","-.--.-"}, {")","-.--.-"}, 
            {"0","-----"}, {"1",".----"}, {"2","..---"}, {"3","...--"}, {"4","....-"}, {"5","....."},
            {"6","-...."}, {"7","--..."}, {"8","---.."}, {"9","----."}};

    public static void toMorse( String s3 ) {
        String translation = "";
        for ( int i = 0; i < s3.length(); i++ ) {
            String c = s3.substring(i, i+1);
            for (int j = 0; j < morseEnglish.length; j++){
                if (morseEnglish[j][0].equals(c)) {
                        if (translation.equals("")) { translation = morseEnglish[j][1]; }
                        else { translation+= " " + morseEnglish[j][1]; }
                }
            }
        }
        System.out.println("Morse Code:  " + translation);
        JOptionPane.showMessageDialog(null, translation, "English To Morse Code", JOptionPane.INFORMATION_MESSAGE);
    }

    public static void toEnglish( String s1 ) {
        String code[] = s1.split(" ");
        String translation = "";
        for (int i = 0; i < code.length; i++) {
            for (int j = 0; j < morseEnglish.length; j++){
                if (morseEnglish[j][1].equals(code[i])) {
                    translation+= morseEnglish[j][0];
                }
            }
        }
        System.out.println("English:  " + translation);
        JOptionPane.showMessageDialog(null, translation, "Morse Code To English", JOptionPane.INFORMATION_MESSAGE);
    }

    public static void main( String [] args) {
        JOptionPane.showMessageDialog(null, "Select OK To Begin Translating:", "Morse Code/English Translator", JOptionPane.INFORMATION_MESSAGE);
        System.out.println("Begin Program");
        String s2 = "";
        while (!s2.toLowerCase().equals("quit")) {
            s2 = UserInput.getString( "Enter either 'To Morse' or 'To English'.\n"
                    + "To Quit enter the word 'Quit':\n(not case sensitive)\n" );
            if (s2 == null) { break; }
            if ("to morse".equals(s2.toLowerCase())  ) {
                String s3 = UserInput.getString( "Please type a phrase in English" );
                if (s3 != null) { toMorse(s3.toLowerCase()); }
            }
            if ("to english".equals(s2.toLowerCase()) ) {
                String s1 = UserInput.getString( "Please type a phrase in Morse Code" );
                if (s1 != null) { toEnglish(s1.toLowerCase()); }
            }
        }
    }
}

Hope this helps a bit.

Community
  • 1
  • 1
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
  • Thank you so much. This helped me understand a lot more about the way to properly write my code. Thank you very much for all the help with this. Is there a way I can send you a direct message about another program with the same message? Once again you have been very helpful and encouraging for me and my coding. @DevilsHnd – Skier1999 Jan 04 '16 at 20:00
  • You are very welcome @Skier1999 and I'm glad it has helped you in some way. Unfortunately, I will not accept private messages regarding assistance to specific code projects or problems within those very same projects. This is what the StackOverflow forum is for. You have a world of professional Java programmers at your fingertips, all you need do is to ask. And always remember, the problems you have had solved here today will solve the very same problems for someone else tomorrow. Chin up Java programmer, you're not alone in the world. :) – DevilsHnd - 退職した Jan 07 '16 at 10:32