Vigenere decryption StringIndexOutOfBoundsException

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hcarlens
    New Member
    • Sep 2007
    • 4

    #1

    Vigenere decryption StringIndexOutOfBoundsException

    Hi all,

    I am having a problem with a vigenere decryption method I am writing.
    I have tried to solve this but really can't figure out why this is happening.
    I get a java.lang.Strin gIndexOutOfBoun dsException and while I know what this means, I don't know why it occurs in this instance.
    The method takes a ciphertext and key string as an argument, and first loops through all letters in the key and converts them to the number they are in the alphabet (e.g. a=0,b=1,etc..). Then it loops though all the letters in the ciphertext and shifts them by the amount given in the key.

    Code:
    public String VigenereDecrypt(String Ciphertext, String Key){
    	int KeyLength = Key.length(); 
    	int[] ShiftAmounts = new int[KeyLength];
    	String Plaintext = "";
    	for(int a=0;a<KeyLength;a++){
    		ShiftAmounts[a] = Alphabet.indexOf(Key.substring(a,1));
    	}
    for(int i=0;i<Ciphertext.length();i++){
    	int ShiftAmount = i % KeyLength;
    	String Sub = Ciphertext.substring(i,1);
    	String ShiftedSub = Shift(Sub,ShiftAmount);
    	Plaintext += ShiftedSub;
    }
    return Plaintext;
    }
    The exact error I am getting is:
    Exception in thread "main" java.lang.Strin gIndexOutOfBoun dsException: String index out of range: -1
    at java.lang.Strin g.substring(Unk nown Source)

    and it occurs at line six of the block of code shown here.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    That substring method invocation is wrong; pay close attention to that second
    parameter value and compare it with String's API documentation.

    kind regards,

    Jos

    Comment

    • hcarlens
      New Member
      • Sep 2007
      • 4

      #3
      I'm sorry for posting something like this on this forum, I didn't realise that my error was this trivial. Thank you for helping me solve this and for not just telling me the answer.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by hcarlens
        I'm sorry for posting something like this on this forum, I didn't realise that my error was this trivial. Thank you for helping me solve this and for not just telling me the answer.
        You're welcome of course. Trivial mistakes are the nastiest mistakes to find
        because, they're so, well, trivial. You don't suspect yourself to make those
        trivial mistakes anymore. I suffer from the same syndrome now and then ;-)

        kind regards,

        Jos

        Comment

        Working...