3

I am trying to convert the word that the user inputs into binary. The program runs correctly, but after the user inputs his/her word there is an error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26 at home.main(home.java:84)

Here is my code:

 import java.util.Scanner;
 import java.util.Vector;

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

    char[] alphabet = new char[]
    {
        '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[] Binary = new String[]
    {
            "00001 ",
            "00010 ",
            "00011 ",
            "00100 ",
            "00101 ",
            "00110 ",
            "00111 ",
            "01000 ",
            "01001 ",
            "01010 ",
            "01011 ",
            "01100 ",
            "01101 ",
            "01110 ",
            "01111 ",
            "10000 ",
            "10001 ",
            "10010 ",
            "10011 ",
            "10100 ",
            "10101 ",
            "10110 ",
            "10111 ",
            "11000 ",
            "11001 ",
            "11010 ",   
    };

    String word;
    System.out.println("Type in what you want to convert into binary: (to exit type in 'quit')");
    while(true)
    {
        Vector<String> wordBin = new Vector<String>();
        word = getWord.next();

        if(word == "quit")
        {
            break;
        }
        for(int a = 0; a < word.length(); a++)
        {
            for(int b = 0; b < 27; b++)
            {
                if(word.charAt(a) == alphabet[b])
                {
                    wordBin.addElement(Binary[b]);
                }
            }
        }

        System.out.println();
        System.out.println("That in binary is: ");
        System.out.println();

        for(int c = 0; c < wordBin.size(); c++)
        {
            System.out.println(wordBin.get(c));
        }

        System.out.println();
        System.out.println("What is the next word that you would like to type in: ");

    }

    System.out.println();
    System.out.println("Hava a nice day");
}
}

I am using Eclipse Mars.1 to run the program. Any help is appreciated.

5
  • 3
    Why don't you people use debugger? It helps a lot to solve issues like these. Commented Nov 7, 2015 at 23:13
  • 1
    Also, capitalize the name of a a class. This is a universally observed convention in Java. Commented Nov 7, 2015 at 23:16
  • 2
    Why did you write b < 27 instead of b < 26? Commented Nov 7, 2015 at 23:20
  • 1
    Why not just: for(char c : input.toCharArray()) result += Integer.asBinaryString((int) c); It'll convert the char to a number via ASCII, then grab the binary form of that number, adding it onto a final result (use StringBuilder to add) Commented Nov 7, 2015 at 23:21
  • Tip: char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray(); Commented Nov 7, 2015 at 23:36

2 Answers 2

3

Your problem is within this code:

for(int b = 0; b < 27; b++)
{
    if(word.charAt(a) == alphabet[b])
    {
        wordBin.addElement(Binary[b]);
    }
}

alphabet only has 26 elements, which means the highest index you are allowed to access is 25. b < 27 allows it to index up to 26.

To fix it, simply change b < 27 to b < alphabet.length. This will ensure it does not exceed the maximum index, even if you were to add/remove elements.


Use ASCII to allow others to decode your message

I suggest using a more universal mapping system. You currently map:

a = 0001 = 1
b = 0010 = 2
...

These are not standards. Your result will not be of use to anyone who doesn't know exactly which letter represents which set of bits. Although they could assume, it's best to use a standard.

Instead, you could use an ASCII table to see which letter maps to which number. From there, you can convert the number into binary. This will make it easier for others to convert it back to it's original form.

String word = "hey";
StringBuilder result = new StringBuilder();
int byteLength = 8;
for(char letter : word.toCharArray()) {
    String bits = Integer.toBinaryString((int) letter);
    if(bits.length() < byteLength) {
        StringBuilder extendedBits = new StringBuilder();
        for(int i = bits.length(); i < byteLength; i++) {
            extendedBits.append("0");
        }
        result.append(extendedBits);
    }
    result.append(bits);
}

System.out.println(result);

Others could then use a binary to text converter to convert it back into letters, since it follows a standard.

This works due to (int) letter returning the ASCII mapping for that letter. If we did

int number = (int) 'h';

It would return 97. From there, we conver that number into binary via Integer.toBinaryString(int).

Since toBinaryString gives a trimmed value (10 rather than 00000010), we must fill in the rest of the space with 0s until there are enough bits to represent a single byte.

Sign up to request clarification or add additional context in comments.

Comments

1

Your if statement uses ==. You should use if(word.equals("quit")). The == operator in Java tests if objects are identical, not just equivalent.

You also see an exception telling you that the bounds of an array have been exceeded.

5 Comments

I think he was mainly asking for the reason why the OutOfBounds appears. Can you explain to him ?
Clearly this is a problem with a loop, which I believe he can spot.
Obviously not ;-) Such a shame, if your answer covered both aspect I could spare a plus one ;-)
This doesn't even answer the question. This answer targets a totally different problem. I highly suggest editing it to target the exception he is getting
This is the culprit: for(int b = 0; b < 27; b++)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.