caesar box with length of non-square...
public static String encrypt(String plainText) {
int a = plainText.length();
// Determining the size of the Array
// Rounding up square root of text length
int SizeOfArray = ((int) Math.ceil(Math.sqrt(a)));
// Setting the size of the Array
char[][] encryptArray = new char[SizeOfArray][SizeOfArray];
for (int i = 0; i < SizeOfArray; i++) {
for (int j = 0; j < SizeOfArray; j++) {
encryptArray[i][j] = plainText.charAt(0);
plainText = plainText.substring(1);
}
}
String putTogether = "";
for (int i = 0; i < SizeOfArray; i++) {
for (int j = 0; j < SizeOfArray; j++) {
putTogether += encryptArray[j][i];
}
}
return putTogether;
}
The code works perfectly with perfect square length
but it gives error with non square length..
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
Please Help!
Re: caesar box with length of non-square...
Quote:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
The code at line 686 is using an index past the end of the String. The index is shown as 0 which means that the String must be empty. The code should test the length of the String before trying to index into it to make sure there are characters in the String.
Please edit your post and wrap your code with code tags:
[code=java]
<YOUR CODE HERE>
[/code]
to get highlighting and preserve formatting.