0

I'll preface this question with the fact that I'm only 1 month into learning programming, and this assignment for school has me stumped. Specifically, it's the Morse Code to English translator (and vice versa)... here's the part I'm stuck on:

/* 
*  A program that asks the user to select which they would like to do: translate 
*  from English to Morse code, or Morse code to English. The list of characters 
*  for each language is stored using arrays. The program will then perform and return
*  the translations.
*/
import java.util.Scanner;

public class MorseEnglishTranslator
{

    public static void main( String [] args )
    {
        int translateChoice = 0;                   // Variable for person's choice for direction of translation

        Scanner inputText = new Scanner( System.in );  // Create a Scanner to obtain user input
        System.out.print( "Enter 1 to translate from English to Morse code, 2 for Morse code to English: " );
        translateChoice = inputText.nextInt();

        if (translateChoice == 1);
            {        
                System.out.print("Enter a letter, word, or phrase you would like translated: ");
            }    
        if (translateChoice == 2);
            {
                System.out.print("Enter the Morse code you would like translated, separate letters and words with a |: ");
            }
        String userStr = inputText.nextLine();

        translator( translateChoice, userStr);


    } // Closes main

    public static void translator( int translateChoice, String userStr) // Method for translating either direction
    {
        String 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 s1 = String.join(" ", english);  // Assigns the contents of english array to one string

        String morse [] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", 
                           "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
                           "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..",
                           "----.", "-----", "|"};

        String s2 = String.join("|", morse);    // Assigns the contents of morse array to one searchable string

        if (translateChoice == 1);
            {        
                String userStrLower = userStr.toLowerCase();  // In case user capitalized anything, changes everything to lowercase
                for (int allFound=0; allFound <userStrLower.length(); allFound ++)
                {
                    allFound = s1.indexOf( userStrLower );  // Variable 'allFound' to receive the search of s1 using userStrLower
                    System.out.print( allFound );
                } 
            }    
        if (translateChoice == 2);
            {
                for (int allFound=0; allFound <userStr.length(); allFound ++)
                {
                    allFound = s2.indexOf( userStr );  // Variable 'allFound' to receive the search of s2 using userStr
                    System.out.print( allFound );
                }   
            }

    } // Closes translator        
} // Closes class

Strings s1 and s2 are the two options I was contemplating using, but the s1 version tells me after New there was an expected semi-colon. The join option, which I tried as String.join vs join, says no suitable constructor vs cannot find symbol respectively.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Michelle_M
  • 45
  • 4
  • 2
    Please state the language you are using. – sschale Mar 01 '16 at 01:48
  • Already done for her, she just needs to accept! – sschale Mar 01 '16 at 01:49
  • It's been a while since I've used Java, but should 'New' be all lowercase or does it matter? Also, can you remove the "etc.", and put a real example so we know exactly what you have. You can make the list smaller, just remove the extra stuff that isn't code. – kojow7 Mar 01 '16 at 01:53
  • Thanks for reformatting my post.. not seeing where to "accept" the edit. When I used new in lowercase the line gave me a no suitable constructor error. – Michelle_M Mar 01 '16 at 01:57
  • Just a translator? Letters as well as numbers? – OneCricketeer Mar 01 '16 at 02:00
  • **s2** needs **new** before it, then use same idea for *s1* – Arif Burhan Mar 01 '16 at 02:00
  • Also, check the docs for how to use join correctly. You are not using it correctly as you can see here: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...- – kojow7 Mar 01 '16 at 02:01
  • Thanks Dijkgraaf. @cricket_007, yes it is all 36 characters for letters and numbers, but this is the part I can't get to compile.. currently at least. – Michelle_M Mar 01 '16 at 02:03
  • Do you actually have the word "etc" in your code? – kojow7 Mar 01 '16 at 02:05
  • 1
    Probably because `new` is lowercased and `etc` isn't valid code. Provide the real code, please so we don't need to copy down all the morse strings – OneCricketeer Mar 01 '16 at 02:05
  • I tried adding the new just now @Arif Burhan, it didn't work. – Michelle_M Mar 01 '16 at 02:08
  • try String s2 = english.join(morse, "|"); – Josua Marcel C Mar 01 '16 at 02:10
  • I'm confused what output you want. Do you just want a direct translator between the arrays, or are you trying to translate whole sentences? – OneCricketeer Mar 01 '16 at 02:11
  • No, @kojow7, just didn't want to paste the whole thing. Although it this point it could only help. So beyond each of the for loops, I thought I could return the indices for each "found" item. And then use those indices to call from the opposite string for the translation. Someone can maybe reformat this again? – Michelle_M Mar 01 '16 at 02:11
  • Whoops, I guess I can't put my whole code into a comment, too long. – Michelle_M Mar 01 '16 at 02:12
  • You can edit your original question and put it in there and also you are able to format it yourself. – kojow7 Mar 01 '16 at 02:13
  • ok, it's there, no one laugh too much please. – Michelle_M Mar 01 '16 at 02:15
  • PS I only added the print statement so I could see some output/that it was working, it wouldn't be included ultimately. – Michelle_M Mar 01 '16 at 02:24
  • So I have code to translate a string to morse, but translating back is more difficult unless the morse is supposed to be delimited by spaces, for example... – OneCricketeer Mar 01 '16 at 02:28
  • You also still need to fix up your join function as per the page I linked you to. – kojow7 Mar 01 '16 at 02:32
  • Yeah, I haven't wanted to think of the challenge of reading through the characters that make up each morse code element. Honestly, this program is well beyond the scope of what we've gone over in class up to this point. It's an Intro to Java class for god's sake. – Michelle_M Mar 01 '16 at 02:32
  • Where did you find out about the s1 option in Java? I have never seen that method before and do not think it's possible. Also, once you fix up your s2, I will help you with the next step. – kojow7 Mar 01 '16 at 02:36
  • It's in the Oracle Java Complete Reference, under creating a String literal. – Michelle_M Mar 01 '16 at 02:44
  • Can you provide me a link to that page? – kojow7 Mar 01 '16 at 02:48
  • Ok, @kojow7, I fixed my join statements and then it wanted me to add a return statement, but I just changed the return type to void to step around that current problem... it compiled, yeah! But then I got a runtime error: Class names, 'MorseEnglishTranslator', are only accepted if annotation processing is explicitly requested... huh? Never had a problem with my class names. – Michelle_M Mar 01 '16 at 02:48
  • It's a hard copy text. – Michelle_M Mar 01 '16 at 02:50
  • Great! Your joins should work fine now! By the way is there a reason that you are wanting to make them into a single string in the first place? – kojow7 Mar 01 '16 at 02:52
  • I think the error you are facing now is coming from how you are compiling it. Are you sure you are specifying ".java" in the filename? – kojow7 Mar 01 '16 at 02:54
  • I thought I had to make them into strings to use indexOf, replace, equals, etc., that I assumed I needed to do some of the other things I was planning. The only absolute part of the assignment was that I use arrays, so no, if I don't need to change to strings, I don't have to. – Michelle_M Mar 01 '16 at 02:56
  • Making them into strings makes things much more complicated. Keep them as arrays. – kojow7 Mar 01 '16 at 02:58
  • 1
    Bah, I'm an idiot! I scrolled in the command prompt to pick my class name and it changed my java to javac. – Michelle_M Mar 01 '16 at 03:00
  • So now that it ran, it let me go through my first prompt, then gave me both my next prompts at once and didn't offer me a chance to input anything, just returned to a new line.. even after I added break statements. – Michelle_M Mar 01 '16 at 03:05
  • This will explain why that's happening and how to fix: http://stackoverflow.com/questions/23036062/cant-use-scanner-nextint-and-scanner-nextline-together – kojow7 Mar 01 '16 at 03:09
  • If you build your reputation up to 20 on StackOverflow it will give access to the chat rooms. – kojow7 Mar 01 '16 at 03:49
  • Considering the project I have due next week, I foresee lots of questions and needed help, lol! – Michelle_M Mar 01 '16 at 04:03
  • Did that above link help you fix your issue with the input? – kojow7 Mar 01 '16 at 04:16
  • Oh, sorry I didn't post... yes I got the input part squared away. Now it's the English to Morse code that is not working. – Michelle_M Mar 01 '16 at 05:00
  • @Michelle_M For the next part, you need to ask yourself "If I were to teach a 7 year old how to convert from letters to morse code just by looking at the two arrays, how would I explain it to them?" You wouldn't tell them that they first need to join it into a big long string of text. Think about how you would teach them to do it on paper (not programming-wise). What steps would they have to follow to come up with the correct answer? Once you answer this you should be able to use that same way in your program. – kojow7 Mar 03 '16 at 03:40

1 Answers1

-1

I understand that you are in an intro to Java class, so feel free to ask questions, but you 1) don't need to join Strings and 2) indexOf is really inefficient for the purposes you need it for. A HashMap<String, String> is the perfect object for a translator.

I have made this bi-directional map class that can go back-and-forth between two String arrays. Save this into a BiMap.java file.

import java.util.HashMap;

public class BiMap {
    private HashMap<String, String> forwardMap;
    private HashMap<String, String> backwardMap;

    public BiMap(String[] from, String[] to) {
        forwardMap = new HashMap<>();
        backwardMap = new HashMap<>();

        for (int i = 0; i < from.length && i < to.length; i++) {
            forwardMap.put(from[i], to[i]);
            backwardMap.put(to[i], from[i]);
        }
    }

    public String translateForward(String key) {
        return forwardMap.get(key);
    }

    public String translateBackward(String key) {
        return backwardMap.get(key);
    }
}

And here is a sample usage of that class. Feel free to add your user-prompting back to it. Using static final modifiers is recommended for class variable constants. Then, I defined some private methods to extract out the translation logic.

It good practice to write readable and reusable methods as much as possible when learning.

public class MorseEnglishTranslator {

    private static final String[] ENGLISH = new String[]{
            "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", " "};

    private static final String[] MORSE = new String[]{
            ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
            "....", "..", ".---", "-.-", ".-..", "--", "-.",
            "---", ".--.", "--.-", ".-.", "...", "-", "..-",
            "...-", ".--", "-..-", "-.--", "--..", ".----",
            "..---", "...--", "....-", ".....", "-....",
            "--...", "---..", "----.", "-----", "|"};

    private static final BiMap MORSE_MAP = new BiMap(ENGLISH, MORSE);

    private static final String DELIMITER = " ";

    private static String toMorse(String s) {
        StringBuilder sb = new StringBuilder();
        String lower = s.toLowerCase();
        for (int i = 0; i < lower.length(); i++) {
            String c = String.valueOf(lower.charAt(i));
            sb.append(MORSE_MAP.translateForward(c)).append(DELIMITER);
        }
        return sb.toString();
    }

    private static String fromMorse(String s) {
        String[] split = s.split(DELIMITER);
        StringBuilder sb = new StringBuilder();
        for (String morse : split) {
            sb.append(MORSE_MAP.translateBackward(morse));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String sentence = "Hello World";
        String morse = toMorse(sentence);
        String translated = fromMorse(morse);

        System.out.println(sentence);
        System.out.println(morse);
        System.out.println(translated);
        System.out.println(sentence.equalsIgnoreCase(translated));

    }

}

Sample run

Hello World
.... . .-.. .-.. --- | .-- --- .-. .-.. -.. 
hello world
true
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Again, thanks so much for the help, but like I told Dongsheng, I have to use arrays, not to mention we haven't gone over Hashmaps or reading external files. – Michelle_M Mar 01 '16 at 03:28
  • I did use arrays, I just created a Hashmap using the arrays. Also not reading external files at all, just made a separate class. You have already used classes, even if you haven't learned what they are – OneCricketeer Mar 01 '16 at 03:43
  • Sorry, I wasn't aware, it's just that we haven't gone over either concept, so I'd be full on cheating. We are just about to go over having multiple classes. At any rate, it's very nice, just not something I can wrap my head around yet, as clearly I'm still having a problem with these "lower" concepts. I will say though, it seems like trying to make this work using only arrays and strings seems overly complicated, compared to the alternatives. :) – Michelle_M Mar 01 '16 at 04:01
  • Yeah. I just want to make you aware of the problem of joining the morse strings. You have | as one of your characters and you are joining all the morse code strings with |, so using `indexOf("|")` will not work because it will return the first | after the morse code for "a" and not the proper index for the | character that should be a space – OneCricketeer Mar 01 '16 at 04:08
  • When you say it that way, it makes sense, I thought by putting it in, it would make it available to read. In the join part I thought I was making it the delimiter our professor was requiring. I just want all of these objects, methods,constructors, etc. to behave like algebraic equations and variables, but that's not how it is, lol. – Michelle_M Mar 01 '16 at 04:58