2

I already posted a topic on this but have considerably (and that topic was put on hold..so I can't edit) changed my code (I tried what one of the users said in different variations, but no beans). I've tried running just toMorse, but although it compiles I get no output and an error message of 'java.lang.ArrayIndexOutOfBoundsException(at projmorsejava:22 and 46)' I'm not sure how to configure toEnglish, at this point I've tried using the replaceAll, indexOf and valueOf methods. I've also tried using plaintextString but that also did not work out (I may have implemented it incorrectly). Here is my revised code:

import java.util.Scanner;

public class ProjMorse
{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String[] alpha = { "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[] dottie = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
                "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
                "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
                "-.--", "--..", ".----", "..---", "...--", "....-", ".....",
                "-....", "--...", "---..", "----.", "-----", "|" };

        System.out
                .println("Enter English to convert from English or Morse to convert from Morse:");

        String ans = input.nextLine();

        if (ans.equals("English")) {
            System.out.println("Please enter the text you would like   to convert to Morse Code: ");
            String english = input.nextLine();

            char[] translates = (english.toLowerCase()).toCharArray();
            System.out.println(toMorse(translates, dottie)); //calls on method toMorse

                }
                        else if (ans.equals("Morse")) {
            System.out
                    .println("Please enter the text you would like to convert to English (separate words with '|'):");
            String code = input.nextLine();

             String[] translates = (code.split("[|]", 0));
                     System.out.println(toEnglish(translates, alpha));//calls on method toEnglish

        }
    else
    System.out.println("Invalid input, please try again.");
     }

       public static String toMorse(char [] translates, String [] dottie)
       {            
      String morse = "";
      for (int j = 0; j < translates.length; j++)
      {
        char a = translates[j];
        if(Character.isLetter(a))
        {
           morse = dottie[a + 'a'];
        }
      }
      return morse;/*so I tried running only this(commented other stuff out) and it compiled but although it ran it didnt translate */
    }

    public static String toEnglish(String [] translates, String  [] alpha)
    {
      String s;
      for (int n = 0; n < translates.length; n++)
      {
        String a = translates[n];
                s = java.util.Arrays.asList(alpha).(Character.toChars(a + 'a')[0]);//I'm not sure what to do here..
      }
      return s;
    }
}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
LongGone
  • 35
  • 1
  • 1
  • 5
  • 5
    These are all very basic syntax errors, indicating you are not yet ready to tackle something of this complexity. I recommend you start with a basic Java tutorial and get all the examples and exercises working. You should also learn to use an IDE such as Eclipse or NetBeans. They will make learning Java much easier. You have a lot to learn, and unfortunately SO is not a tutorial site. You should also look at the [FAQ] and [Ask] pages. – Jim Garrison Jan 03 '14 at 22:58
  • I know they are.. I've read so much and it's due in only a few hours.. I've worked on it for days at length..Thank you so much! – LongGone Jan 03 '14 at 22:59
  • 4
    I'm sorry for you. If it's due in a few hours then you are not going to get it working, and SO most definitely won't help you cheat. Ask your teacher for help and/or sympathy. At this late date that's about all you can do. – Jim Garrison Jan 03 '14 at 23:01
  • 1
    I formatted your code a little so error lines can now be not the same. But now at least everyone can read your code easier. – Pshemo Jan 03 '14 at 23:02
  • `Main.java:18: error: cannot find symbol System.out.println(toMorse(morse));` NOT due to other errors. Read the error message again. You have not defined `morse`. The `^` on the line below the error points to exactly where the error is. – dansalmo Jan 03 '14 at 23:03
  • @JimGarrison I'm not trying to cheat!! I just want to figure out what I'm doing wrong.. I've really worked super hard on this and have tried conacting my instructor numerous times before resorting to SO I know I'm doing some kind of return error, but I've looked through all of my textbook and don't know what exactly is going wrong.. – LongGone Jan 03 '14 at 23:06
  • 1
    What is `morse` in `System.out.println(toMorse(morse));`? What is `s` in `System.out.println(toEnglish(s));`? Does `char[]` have `valueOf` method? Is there `string` type in Java? – Pshemo Jan 03 '14 at 23:09
  • @Pshemo Oh yeah I changed the string to String in my program.. forgot to edit it here. s and morse are the strings defined in the methods toMorse/toEnglish – LongGone Jan 03 '14 at 23:13
  • @user3151732 if you define variable inside code block, like the one of method it becomes [local variable](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html) which is not accessible in other methods. – Pshemo Jan 03 '14 at 23:18
  • @Pshemo Yes, I know that, but shouldn't it be okay if I return the variable? – LongGone Jan 03 '14 at 23:21
  • @user3151732 By returning method returns value of variable, not variable itself. – Pshemo Jan 03 '14 at 23:25
  • FYI: if a question is put [on hold] then you can and should edit the question to resolve the problem. If you do this, then the hold may be removed. Do not just try again with a new question. – Kevin Panko Jan 04 '14 at 02:47
  • @Kevin Panko, I did try this but it was not reopened...and it was over 2 days.. i looked through all they posted within the reasons and did my best to revise it.. – LongGone Jan 04 '14 at 02:49

2 Answers2

1

There are several things that do not work:

  1. missing initial public class ... (I suspect a copy-paste error)
  2. missing import java.util.Scanner; since you use Scanner
  3. wrong call to toMorse: first, two args are expected (check the method signature); then, first argument's name is not morse (unknown symbol), it must be translates, which you have just "created"! About the second: you need the array of strings that has in place of the e.g. "e" the morse code, so second argument must be... dottie
  4. wrong call to toEnglish: two args required (check the method signature, as done before!); the first, has to be translates, again (unknown s, as morse before)! About second argument: see above but of course since you have morse in input, you need the other array.
  5. in toMorse you pick each char using translates[j], not valueOf.
  6. similarly, in toEnglish you get the string using translates[n]
  7. in both toEnglish and toMorse, you have to "accumulate" the converted string into a string, and return it at the end, i.e. outside the loops!
  8. having a string, you pick the char at pos 0 using .charAt(0): to perform an op like x - 'a' x can't be a string, so since you have a string, you must get its first char.
  9. Note: about your using of morse and s: variable names in a method has nothing to do with variable names in the caller!

Example for toMorse:

    String morse = "";
    for (int j = 0; j < translates.length; j++)
    {
        char a = translates[j];
        if(Character.isLetter(a))
        {
            morse += dottie[a - 'a'];
        }
    }
    return morse;  // this symbol is unknown to the caller

You will call it with something as simple as

              System.out.println(toMorse(translates, dottie));

The fix for toEnglish is very similar (though your original code won't work), I hope you can do it by yourself.

I think is all, more or less.

Suggestion to fix toEnglish:

For each string you have in your translates array, you have to search into dottie string array in order to search for that particular sequence of dots and lines.

If you find it, the position (index) you find it at, it's also the index of the right letter you keep in the alpha array. So you might need to add that array as argument and use the index to pick the letter.

Or, rather, you can use the same "trick" you used to toMorse and keep the toEnglish method signature unchanged: once you have the index, since you have found it, you can "invert" the coding algorithm, so you have to add 'a' to that index (integer) to obtain the code for the letter.

You can use something like Character.toChars(k + 'a')[0] to take the char you want to add to the "accumulation string", being k the index.

The cumbersome notation Character.toChars(k + 'a')[0] is since indeed Character.toChars returns an array, so we pick the first element of that array, which is the char we need.

ShinTakezou
  • 9,432
  • 1
  • 29
  • 39
  • Thank you, I'll definitely look into this(: – LongGone Jan 03 '14 at 23:22
  • 1
    I should explain some point longer, but feel lazy about it. It's important you focus on your errors and try to ask yourself if there's any basic knowledge you miss to get it right. E.g. why did you think you needed something like `valueOf`? – ShinTakezou Jan 03 '14 at 23:26
  • I thought that by using valueOf I could access the corresponding value in the index of the other array and switch it.. Even so, I originally tried using the "replceAll" method but that didn't work either. – LongGone Jan 03 '14 at 23:30
  • valueOf is a static method in String, and it's used to get a string representation of a value. Here you have an array of chars or strings, and you have just to pick the right value which is in the relevant position (index) that you "compute". Be sure to get how the toMorse and toEnglish loops work! -- indeed I am noting now that toEnglish likely won't work – ShinTakezou Jan 03 '14 at 23:36
  • so to fix my errors I should use indexOf? I also tried that..it didn't work. yeah, I realize that. I tried something along the lines of this(for both methods): plaintextString.replaceAll(c, dottie[characterIndex]); characterIndex++; this didn't work either.. – LongGone Jan 03 '14 at 23:38
  • would something like this be the correct call for toMorse char [] translates = new char(toMorse(dottie[morse]); or would it be translates = new char(toMorse(translates[(dottie[morse])]); – LongGone Jan 03 '14 at 23:45
  • you can use `java.util.Arrays.asList(dottie).indexOf(a)`, see [this](http://stackoverflow.com/questions/6249537/indexof-in-a-string-array) or [this](http://stackoverflow.com/questions/4962361/where-is-javas-array-indexof). `replaceAll` won't give you easily what you want. You call toMorse like... going to mod the ans... – ShinTakezou Jan 03 '14 at 23:52
  • going to mod the answer?? What do you mean? – LongGone Jan 03 '14 at 23:56
  • that I have modified my answer slightly to answer your last question in your last comment. – ShinTakezou Jan 03 '14 at 23:58
  • Thanks again, I'll see what I can do(: and if it doesn't work out, you'll be here, right? – LongGone Jan 04 '14 at 00:00
  • Also, wouldn't I call alpha in toEnglish? just making sure.. – LongGone Jan 04 '14 at 00:11
  • I've expanded a bit the answer in order to address this last Q too... And I promise its the last edit: really too late to keep focused!! – ShinTakezou Jan 04 '14 at 00:18
  • `java.util.Arrays.asList(dottie).indexOf(a)` would this simply get the index of dottie at a? – LongGone Jan 04 '14 at 00:20
  • it will give the index at which the string equal to a is found in the array. if the string a is not found in the array, the index will be negative (-1). – ShinTakezou Jan 04 '14 at 00:22
  • Do I still need to return morse and s? – LongGone Jan 04 '14 at 00:29
  • of course, yes!! Pick your book or lessons notes and check the pages about function/method calls, return values and so on! – ShinTakezou Jan 04 '14 at 00:35
  • but even though I return them, they don't go anywhere?.. as my method calls translates and the other corresponding array? also, this shoudl be my statement for toEnglish,correct?: `alpha.Character.toChars(a + 'a')[0]` – LongGone Jan 04 '14 at 00:37
  • when I try to compile it cannot find 'morse' in return morse.. `String morse = dottie[a + 'a']; } } return morse;` – LongGone Jan 04 '14 at 00:42
  • you can't use sumbol morse outside its scope, delimited by the enclosing `{}`. If you look at the fragment I gave you in the answer, you see I put `String morse = ""` outside, so that it's visible at the end, when you have to return. You are missing very basic knowledge! I suggest you to stop a moment writing code and to return to a little bit of theory from books and lessons notes, whatever you have! – ShinTakezou Jan 04 '14 at 00:52
  • Oh, I see that now, I must have skipped over it, okay, I understand now..yes, it's only a local variable.. Thank you it all makes a bit more sense.. I'm still not sure how to implement Character.toChars into alpha.. Thanks again and sorry for all the questions. – LongGone Jan 04 '14 at 01:02
  • would I do something like alpha[Character.toChars]? I tried many different variations to no avail. – LongGone Jan 04 '14 at 18:44
  • I tried running only the toMorse part and it compiled but did not give any output.. – LongGone Jan 04 '14 at 20:24
  • At this point it's not clear what are you trying to run. The code, with the fixes, if you have applied them correctly, works (I've just run it with `English`, `SOS` as input, obtaining `...---...` as output). Once toMorse returns the string, of course you need to output it in order to see anything. – ShinTakezou Jan 05 '14 at 01:09
  • wouldn't my output just be `System.out.println(toMorse(translates, dottie))` ? also my code here has been updated to it's current version.. – LongGone Jan 05 '14 at 01:11
  • [yes](http://pastebin.com/z0TYSU2z) it is. So? Maybe you did something else wrong? – ShinTakezou Jan 05 '14 at 01:16
  • Okay, it worked, but it's not putting in a '|' for the spaces when translating to morse and when translating to english where there is a '|' it doesn't add a space(isn't splitting the string sufficient to add the space?).. – LongGone Jan 05 '14 at 01:33
  • if you aren't able to add some `|` in toMorse output, or spaces in toEnglish... sorry but I give up: it'd mean I have to complete all the exercise for you, in all its details, and it'd be unfair — I've already done more than conceivable, the rest *must* be done by you. – ShinTakezou Jan 05 '14 at 01:38
  • 1
    That's true..I shall figure it out. Thank you so much for all of your help(: It really has helped me, not only with programming, but understanding how far little things can go(: And that it doesn't always have to be so very complicated. – LongGone Jan 05 '14 at 01:39
0

Its important you work out these errors by yourself to learn the necessary debugging skills that programming requires. This probably isnt what you are looking for but:

  1. Always start at the first error and work your way down the list.
  2. When you encounter an error message and you dont know what the heck is going wrong take a look at some code samples. Look up "java how to (enter what your trying to do here)" the is a ton of information out there. When choosing what to search make sure you break it down to its most basic form, such as "java how to convert integer to string"
  3. Use a IDE, it may take a bit to get used to but it will be well worth the investment. Theres a very simple looking one called http://www.jedit.org/ it would be right up your alley
ug_
  • 11,267
  • 2
  • 35
  • 52
  • Thank you, I actually have been doing that and sifting through the text and index (literal index :)) but haven't been able to figure it out. I really appreciate your time and effort(: – LongGone Jan 03 '14 at 23:19