Hello. As a personal project, I am trying to create a "Java Argot" translator. However I am having some issues.
The purpose of the program is to translate a sentece into the following "Secret Languages": "Pig Latin", "Leet" and "Morse Code". I have only done the "Pig Latin" translator however, everytime I try to activate case one in the "switch case" I get the error message "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0".

The program shows that the line of code that is sending this message is these two lines: "PigLatin_Translator.main(word);" in the "Translator Menu" and "if(word[count].charAt(0) == 'a' || word[count].charAt(0) == 'e' || word[count].charAt(0) == 'i' || word[count].charAt(0) == 'o' || word[count].charAt(0) == 'u')" in the "PigLatin_Translator". I don't know why the system has an "Index Out of Bounds" error when the program does not give the user a chance to type in a string of code (if it allowed the user to type in a string of code then it would have an index). Please Help. Thank You.

Main Menu for Translator Code (some parts of code are removed since no translator is available yet for the other switch cases

        Scanner scan = new Scanner (System.in);

        System.out.println("****Welcome to the \"Argot \" translator. A translator that translates some common and un-common forms of \"Secret Language\"**** ");
        System.out.println("|Look below at the menu to naviage to which translator you would like to use...");
        System.out.println("|Translator Name                  |        Transator Number|");
        System.out.println("|The \"PigLatin\" Translator        |        Press \"1\" on your keyboard to activate|");
        System.out.println("|\"The \"Morse Code\" Translator     |        Press \"2\" on your keyboard to activate [Comming Soon]|");
        System.out.println("|\"The \"Leet\" Translator           |        Press \"3\" on your keyboard to activate [Comming Soon]|");
        int option = scan.nextInt();

        //Switch case that navigates though translator options
        switch(option){

        case 1:
            //Asks user to type in a sentence for the translator
            System.out.print("Type in a word so it can be translated into \"Pig Latin \": ");
            String wordTyped = scan.nextLine(); 

            //Sends the letter to all Lowercase
            String wordLowercae = wordTyped.toLowerCase();

            //Separates string of words into different words
            String[] word = wordLowercae.split(" "); 

            PigLatin_Translator.main(word);

            System.out.println();

            //Tells the user the "PigLatin Translation
            System.out.print("Here is the \"Pig Latin \" translation: ");

Pig_Latin Translator Code

    public static void main(String[] word) {

    Scanner scan = new Scanner (System.in);

    //Loop that controls the separated words
    for (int count = 0; count < word.length; count++ ) {

        //Pig Latin Rule for "Vowels" (excluding "Y")
        if(word[count].charAt(0) == 'a' || word[count].charAt(0) == 'e' || word[count].charAt(0) == 'i' 
                || word[count].charAt(0) == 'o' || word[count].charAt(0) == 'u') {

            String newWord = word[count] + "-yay";
            System.out.print(" " + newWord);

        }

Recommended Answers

All 17 Replies

Time to debug your code. I don't see it but if this was mine then in Pig_Laten Translator Code just before line 9 I'd add

System.out.print(count); // just to be sure what this is.
System.out.print(word[count].length()) //could it be a null length?
System.out.print(word[count]); // to see what this is.

Thank You. That sounds like somthing I may have to do. I tried using te "Debuger" in my "IDE" called "Eclipse" but I have yet to master what it is used for. How woud I use this tool in my Java code (or would i be easier to just use your suggestion)?

Sorry but if the IDE is broken I'd research that. I'm sure there are tutorials about Eclipse and such so I'll share the old fashioned debug ways instead.

It's a well-known problem with Scanner's design - so many people fall into this trap.

your nextInt reads the menu number, leaving its newline character in the input buffer. The nextLine reads that and returns a zero-length String. See below for more discussion.

You have some input with an int followed by some text, eg
101
John Doe
... and you try to read it with
int num = scanner.nextInt();
String name = scanner.nextLine();
... and name is an empty String ("")!

Here's why:
Your input looks like this with the new line characters shown explicitly
101\nJohn Doe\n
nextInt takes the int value from the scanner, and stops when it finds a chaacter that's not part of an int, so it takes the "101", leaving this in the scanner
"\nJohn Doe\n"
then nextLine takes everything up to the first \n character - a zero-length String ("").

Possible fixes:

  1. Add add extra nextLine() between the nextInt and the real nextLine to clear the unwanted \n. This may be difficult if the nextInt and the nextLine are in different areas of code which are not always executed together.

  2. Give up on nextInt (etc) and just read whole lines and parse then into ints (etc) with Integer.parseInt (etc) - in which case you can junk the whole scanner and use a BufferedReader instead.
    new BufferedReader(new InputStreamReader(System.in))

  3. Use this class instead of Scanner:
    https://www.daniweb.com/programming/code/506346/a-simpler-safer-alternative-to-java-util-scanner

Thanks. It turns out that I just needed a "nextLine()" to clear the scanner however I guess in the future I will try other ways of using the scanner like the "BufferReader" or the article's example of how to use "The Class" and not the Scanner?

Yeah. I would just move on now, and remember that Scanner nextInt and nextLine don't mix well!

Thanks JamesCherrill.

My comment is to think defensively when coding as above. I think the code will fail with null strings so some check would be needed to avoid that in some cases.

That is, I've seen apps run for years and then one day blow up because a check was left out for the out of bounds condition.

I guess coding "defensively" is true since I sometimes I try avoiding the time needed to type "pseudo code" and other preparations for coding (ex: possible "UML Diagram") whenever I can. After you mentioned that some "app's" can run along time before people realize there is an error in it, I started thinking that I should start trying do things like "debug" and more in my code even in class assignments. Regardless, thanks for helping.

The truth is that a minute spent thinking before coding saves ten minutes debugging after coding.
It doesn't have to be complicated or formal. Personally I start by coding my method signatures and a few comments that describe how I see the code working. Call that pseudocode if you like, but it flows seamlessly into completing the real code.
I also start with a lot of assert statements, especially around the values passed into methods. These immediatly document the pre-conditions for the code that will follow, and provide runtime confirmation that those conditions are not being violated.

My comment is to think defensively when coding as above. I think the code will fail with null strings so some check would be needed to avoid that in some cases

Absolutely. For example, I happened to notice that this code will fail if there are two spaces between the words in the input. Other coders may spot other possible failures, based on their own unique backgrounds. In any case a statement like myArray[0] or charAt[0] needs to be protected against zero length arrays or Strings.
Same thing goes for possible null values - the biilion dollar mistake. (Swift is so much better, with not-nullable variables unless explicity declared as nullable. I'd love to see that in a future Java.)

commented: I didn't see that as my brain halted on the null and didn't look further. Two Spaces? Sounds like a movie title. +15

I guess I have another question regarding this same code I have been working on. In the "Translator Menu" I tried to put a "While Loop" around the "Switch Case"(and use a "boolean" variable that equals true at the start of the program to control the "While Loop". For example, While(back_to_menu == true) ) so that the code will continue to loop till the person presses "Zero" to exit the code (I added a "case zero" to the switch case to control the "exit function" now). The code will go though the "switch statement" once then later show an error message that says "No Such Element Exception".

I went online to see why these errors appear and what the possible solution could be. I saw a suggestion that said to remove the line of code that closes the scanner. I did this and it seemed to work however this happend: the code loops around again only to have the line of code that holds the variable called "option" throw the same error. Does anyone any suggestions on what I could use to solve this problem (should I post the newly written code first and write a more detailed explanation regarding the error I am getting)? I'm not an expert at Java or coding but I want to get better at this so please help.

Without seeing the code its impossible to say what's wrong with it!

Sorry about that. Here is the full code (the code is really long. Sorry.):

//Main Argument for program
    public static void main(String[] args) {

        //Activates scanner in the code
        Scanner scan = new Scanner(System.in);      

        //Allows user to go back to main menu
        boolean back_to_menu = true;

        //Tells what computer should do if user wants to go back to the main menu
        while(back_to_menu = true) {
            System.out.println();
            //Shows how to navigate for the menu
            System.out.println("****Welcome to the \"Argot \" translator. A translator that translates some common and un-common forms of \"Secret Language\"**** ");
            System.out.println("Look below at the menu to naviage to which translator you would like to use...");
            System.out.println();
            System.out.println("The \"PigLatin\" Translator: Press \"1\" on your keyboard to activate");
            System.out.println("The \"Morse Code\" Translator: Press \"2\" on your keyboard to activate [Comming Soon]");
            System.out.println("The \"Leet\" Translator: Press \"3\" on your keyboard to activate [Comming Soon]");
            System.out.println("Exit Translator: Press \"0\" on your keyboard to Exit the translator   ");
            //Allows user to choose which translator they want to activate
            int option = scan.nextInt();

                //Switch case that navigates though translator options
                switch(option) {

                //Turns off translator
                case 0:
                    System.out.println("Thank You for Using the \"Argot Translator\"");
                    System.exit(0);

                    //Pig Latin Translator
                case 1:

                    //Clears the scanner so that new input can be typed
                    scan.nextLine();

                    //Asks user to type in a sentence for the translator
                    System.out.print("Type in a word so it can be translated into \"Pig Latin \": ");
                    //Stores the sentence typed by the user in this string
                    String wordTyped = scan.nextLine(); 

                    //Sends the letter to all Lowercase
                    String wordLowercae = wordTyped.toLowerCase();

                    //Separates string of words into different words
                    String[] word = wordLowercae.split(" "); 

                    //Tells the user the "PigLatin Translation
                    System.out.print("Here is the \"Pig Latin \" translation: ");

                    //Sends the sentence typed in my the user to the pre-made Pig Latin translator
                    PigLatin_Translator.main(word);             
                    System.out.println();
                    break;

                case 2:
                    System.out.print("\"Morse Code\" Translator Comming Soon");
                    break;

                case 3:
                    System.out.print("\"Leet Code\" Translator Comming Soon");
                    break;

                case 4:
                    System.out.print("\"Pig Greek Code\" Translator Comming Soon");
                    break;

                default:
                    System.out.print("Invalid");
                }
            }

    scan.close();       
    }
}

Here is the error that I get:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at translator_Program.Translator_Menu.main(Translator_Menu.java:53)

....Thanks for helping

It would be uselful to print option before the switch.
But line 11 you have an assignment where you should have a equals test,.
And even if you fix that then someBooleanExp == true is EXACTLY the same as someBooleanExp

Ok. So I changed the boolean assignment to "==" and not "=". I printed the "option" variable before the switch case. It prints out correctly however the error message shows up once again before the code can loop around and show what the variable "option" will print the second time around. Is there a better way to do this? If there is I will take any suggestions. Here is a sample run of my code just in case:

Welcome to the "Argot " translator. A translator that translates some common and un-common forms of "Secret Language"
Look below at the menu to naviage to which translator you would like to use...

The "PigLatin" Translator : Press "1" on your keyboard to activate
The "Morse Code" Translator: Press "2" on your keyboard to activate [Comming Soon]
The "Leet" Translator: Press "3" on your keyboard to activate [Comming Soon]
Exit Translator: Press "0" on your keyboard to Exit the translator

Note: these translators are mostly a "general" translation regarding since there are several versions of these languages
1
For testing only. The variable "option" prints: 1

Type in a word so it can be translated into "Pig Latin ": cool
Here is the "Pig Latin " translation: ool-cay

Welcome to the "Argot " translator. A translator that translates some common and un-common forms of "Secret Language"
Look below at the menu to naviage to which translator you would like to use...

The "PigLatin" Translator : Press "1" on your keyboard to activate
The "Morse Code" Translator: Press "2" on your keyboard to activate [Comming Soon]
The "Leet" Translator: Press "3" on your keyboard to activate [Comming Soon]
Exit Translator: Press "0" on your keyboard to Exit the translator
Note: these translators are mostly a "general" translation regarding since there are several versions of these languages

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at translator_Program.Translator_Menu.main(Translator_Menu.java:52)

Aha! Just spotted it... You open a second Scanner using the same input stream in your translator method. That "steals" the stream from the first scanner, so the first scanner never sees any more input and throws a NoSuchElement exception when it trys to execute a nextInt()

Ok. I will look at the code again and any "duplicate Scanners" I see (it might be the scanner in the "PigLatin_Translator.main(word)" portion of the code or somewhere else) I will remove. Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.