[Logo] JCVSForum - Community Support For JCVS Users and Developers
  [Search] Search   [Recent Topics] Recent Topics   [Hottest Topics] Hottest Topics   [Members]  Member Listing   [Groups] Back to home page 
[Register] Register / 
[Login] Login 
Messages posted by: buona
Forum Index » Profile for buona » Messages posted by buona
Author Message
Hi, I have this code and I don't know how to solve the out of bounds exception. Can you help me?

public class CodeMachine {
static Random random = new Random();

// swaps array elements i and j
public static void exch(char[] a, int i, int j) {
char swap = a[i];
a[i] = a[j];
a[j] = swap;
}

// take as input an array of char and rearrange them in random order
void shuffle(char[] alphabet) {
int n = alphabet.length;
for (int i = 0; i < n; i++) {
int r = i + (random.nextInt(n - 1)); // between i and n-1
alphabet[i] = (char) (n + random.nextInt(n));
exch(alphabet, i, r);
}
}

public String createNewCode() {
char[] alphabet = { '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' };

shuffle(alphabet);
return alphabet.toString();
}

public String encode(String input) {
StringBuilder builder = new StringBuilder(input);
translate(builder, "abcdefghijklmnopqrstuvwxyz", createNewCode());
return builder.toString();
}

public String decode(String input) {
StringBuilder builder = new StringBuilder(input);
translate(builder,createNewCode(), "abcdefghijklmnopqrstuvwxyz");
return builder.toString();
}

void translate(StringBuilder text, String plainAlphabet,
String codedAlphabet) {
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
char lower = Character.toLowerCase(ch);
int plain = plainAlphabet.indexOf(lower);
if (plain != -1) {
char codeA = codedAlphabet.charAt(plain);
if (Character.isUpperCase(ch)) {
codeA = Character.toUpperCase(codeA);
}
text.setCharAt(i, codeA);
}
}
}

}
 
Forum Index » Profile for buona » Messages posted by buona
Go to:   
Powered by JForum 2.1.9 © JForum Team