0

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);
    }
}
Spencer Uresk
  • 3,730
  • 26
  • 23
user1560400
  • 3
  • 1
  • 1
  • 4

1 Answers1

1

Your do...while loop has an off-by-one error. You check to see if cnt is 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 for String.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:

tacos

This 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 increment cnt to 6. Then you call String.charAt() with a value of 5 (6 -1), but the range of tacos is 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:

    do
    {
        letter = word.charAt(cnt);

        if (letter=='a'||letter=='i'||letter=='e'||letter=='u'||letter=='o')
        {
            letter='$';
        }
        cnt++;
    } while(cnt<word.length());

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.

Spencer Uresk
  • 3,730
  • 26
  • 23
  • 1
    thank you yes its a summer project well one of a set of five in a project but that's all i needed it just an error that i had never seen and it compiled so being a beginner i didn't know what to do.so thank you for taking the time to help. – user1560400 Jul 29 '12 at 18:58