Han Duong Dinh
Han Duong Dinh

Reputation: 1

I don't know why I got index out of bound at test.charAt(1)

    import java.util.*;
    public class Kata {
    public static void main(String[]args)
    {
     Scanner scan = new Scanner(System.in);
     System.out.println("Enter a text to encrypt:");
     //to read the whole line
     String text = scan.nextLine();
     System.out.println(encryptThis(text));
    }
    public static String encryptThis(String text) {
     //words are separated by just one white space between them. 
     //In order to split it and get the array of words, just call the split()

     String [] array = text.split("");
     String encrypt = "";

     for(int j = 0; j < array.length;j++)
     {
            String test = array[j];
            //get first character
            char first = test.charAt(0);
           //convert the first character into ASCII code;
            int ascii = (int) first;

           encrypt+=ascii;
          char second = test.charAt(1);
          char last = test.charAt(test.length()-1);

              encrypt+=last;
              for(int i = 2; i < text.length()-1;i++)
              {
                  encrypt+=test.charAt(i);
              }
              encrypt+=second + " ";               
      }
    return encrypt;
    } 
    }

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 I don't know why I have index out of bound please help.I'm trying to write a program to encrypt messages

Upvotes: 0

Views: 37

Answers (2)

QuickSilver
QuickSilver

Reputation: 4045

Add a check before you access the character at the position

char second = null;
if(test.length > 1) {
  second = test.charAt(1);
}

Upvotes: 0

BeardAspirant
BeardAspirant

Reputation: 79

String test = array[j]; only takes the jth character of array and doing a test.charAt(1) will fail the code. Write a couple of print statements around that to debug further

Upvotes: 1

Related Questions