Results 1 to 3 of 3
  1. #1
    hpayandah is offline Member
    Join Date
    Nov 2010
    Posts
    1
    Rep Power
    0

    Default Array out of bound- Recursive Method

    Java Code:
    public class rot13a
    {
      public static char[] cipher (char x[], int n)
      {
        if (n==0){
          if (x[n] >= 'a' && x[n] <= 'm') x[n] += 13;
          else if (x[n] >= 'n' && x[n] <= 'z') x[n] -= 13;
          else if (x[n] >= 'A' && x[n] <= 'M') x[n] += 13;
          else if (x[n] >= 'N' && x[n] <= 'Z') x[n] -= 13;
          return x;
        }
        
        else{
          if (x[n] >= 'a' && x[n] <= 'm') x[n] += 13;
          else if (x[n] >= 'n' && x[n] <= 'z') x[n] -= 13;
          else if (x[n] >= 'A' && x[n] <= 'M') x[n] += 13;
          else if (x[n] >= 'N' && x[n] <= 'Z') x[n] -= 13;
          return cipher(x,n-1);
        }
      }
      
      public static void main (String args[])
      {
        char str[]=ITI1120.readCharLine();
        int n=str.length;
        char a[];
        a = cipher(str, n);
        System.out.println(a[0]);
      }
    }
    Can't seem to get where I'm going wrong in this code. Help urgently needed, thank you.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Your array x has length n which means that array x holds 0 to n-1 items, and then in your code you're trying to get item x[n] which should understandably cause an array out of bounds error.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    One solution is to call your method with n-1:
    Java Code:
          a = cipher(str, n-1);
    Myself, I like to to rot13 by shifting letters over by 'a' or 'A', adding 13, getting the result modulo 26, and adding 'a' or 'A' back.

Similar Threads

  1. Array index Out of bound Exception
    By nitin_daviet88 in forum New To Java
    Replies: 9
    Last Post: 07-28-2010, 05:32 AM
  2. Array Index Out of bound exception
    By abhijit in forum Networking
    Replies: 7
    Last Post: 09-25-2009, 07:25 PM
  3. Recursive method using int array, help needed
    By chupalo17 in forum New To Java
    Replies: 4
    Last Post: 09-07-2009, 11:15 PM
  4. Replies: 1
    Last Post: 02-16-2008, 09:10 PM
  5. Replies: 2
    Last Post: 02-16-2008, 08:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •