Reputation: 173
FIXED:
I removed my while loop and added
if (num.contains(count) == true) {
freq = Collections.frequency(num, count);
for (int k = 0; k < freq; k++) {
sb.append(temp);
}
}
I'm trying to add a random (well between 0-8) additional copies of letters to a word. Example... does could turn into dddooees or doeess.
My function works sometimes, but always crashes with an Out of Bounds index error.
I'm assuming I need to check for a NULL value my ArrayList at some point. I tried wrapping my while statement with and if to check for it, but no improvement was made. Any suggestions?
private static String addLetters(String word) {
StringBuilder sb = new StringBuilder(word.length());
String[] apart = word.split("");
int rand = (int)(Math.random() * 8);
int ran, goUp;
int count = 0;
List<Integer> num = new ArrayList<>();
for (int i = 0; i < rand; i++) {
ran = (int)(Math.random() * word.length());
num.add(ran);
}
Collections.sort(num);
for (int temp : num) {
System.out.println(temp);
}
for (String temp: apart) {
goUp = count;
sb.append(temp);
System.out.printf("String so far: %s\n", sb.toString());
System.out.printf("OUTSIDE: count: %d, goUp: %d\n", count, goUp);
/*
Removed the while loop and added in the above code using collections, works as intended now.
*/
while (count == num.get(goUp)) {
System.out.printf("INSIDE: count: %d, goUp: %d\n", count, num.get(goUp));
sb.append(temp);
System.out.printf("String ADD extra: %s\n", sb.toString());
goUp++;
}
count++;
}
return sb.toString();
}
Upvotes: 0
Views: 1956
Reputation: 11884
Your loop is on word input (size) and you doing a num.get(goUp)
on num (rand part) if word input size is more big than rand size you have this error (line 41):
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at com.sgr.games.Stack.addLetters(Stack.java:41)
at com.sgr.games.Stack.main(Stack.java:10)
L39 System.out.printf("OUTSIDE: count: %d, goUp: %d\n", count, goUp);
L40
L41 while (count == num.get(goUp)) {
L42 System.out.printf("INSIDE: count: %d, goUp: %d\n", count, num.get(goUp));
Upvotes: 1
Reputation: 9093
Array index out of bounds errors should normally be handled by fixing the bug.
Your logic is confusing enough that I'm not sure exactly how your code is supposed to work. However, I do see your crash:
Compare the purpose of the num array as shown by how you fill it with the purpose that it is being used for in the conditional of the while statement. You are obviously using it in two different fashions.
Upvotes: 0