so i am trying to wright a program to Print a word with all of the vowels replaced with $.
in java.
i keep getting this error exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range: 6 when i run it, it compiles fine.
here’s the code.
import java.util.*;
public class SummerFour
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int cnt = 0;
String word;
String output = "";
char letter = 'x';
System.out.print("enter word to test: ");
word = keyboard.nextLine();
do {
cnt++;
letter = word.charAt(cnt - 1);
if (letter == 'a' || letter == 'i' || letter == 'e' || letter == 'u' || letter == 'o')
{
letter = '$';
}
}
while (cnt <= word.length());
System.out.println(word);
}
}
Your do…while loop has an off-by-one error. You check to see if
cntis less than or equal to the size of the string, then increment it by one and take that value – 1 to use as the index forString.charAt(). This is problematic because Strings are indexed starting at 0, so at the end of a String, you’ll always go one too far.Think about this example:
tacosThis is a five-letter word. When
cnt = 5, you’ll go back through the loop one more time (since 5 is less than or equal to 5) and incrementcntto 6. Then you callString.charAt()with a value of 5 (6 -1), but the range oftacosis only 0-4 (0 = t, 1 = a, 2 = c, 3 = o, 4 = s) and thus 5 is out of range. You can make your do…while loop work properly and look less confusing by doing something like this:Of course, the code still doesn’t do what you want it to, but you no longer get the original error. Since this looks like it might be homework, I’ll let you continue to work through it.