Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: StringIndexOutOfBounds exception

  1. #1
    Junior Member
    Join Date
    Nov 2013
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default StringIndexOutOfBounds exception

    I'm trying to make a program that analyzers strings for certain pieces of information such as the length of the string, the number of vowels, and the number of words. However, while trying to analyze for the number of vowels in the string, I ran into an error. I tried figuring out what was going wrong on my own, but I couldn't seem to find what my problem was. If anyone would care to look through and see what I was doing wrong, it'd be greatly appreciated. The error code is posted below the program code. I am able to compile and run the program, but whenever I enter any piece of data, the program crashes from a StringIndexOutOfBounds exception. This is my first post on this forum by the way, so if I did anything wrong or didn't include necessary information, I'm sorry Just message me back and I'll try to fix it.

    import java.util.*;
     
    class ClrScrn {
        static void clrScrn() {
            for(int lineCounter = 0; lineCounter <= 75; lineCounter++) {
                System.out.println();
            }
        }
    }
     
    class Analysis {
        int vowelCounter(String userString, int stringLength) {
            char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
            int numOfVowels = 0;
     
            for(int stringCounter = 0; stringCounter <= stringLength; stringCounter++) {
                char stringFocus = userString.charAt(stringCounter);
     
                for(int vowelCounter = 0; vowelCounter <= 9; vowelCounter++) {
                    if(stringFocus == vowels[vowelCounter]) numOfVowels++;
                }
            }
     
            return numOfVowels;
        }
    }
     
    class Input {
        String getString() {
            Scanner scan = new Scanner(System.in);
     
            String userString = "";
     
            do {
                System.out.print("Please enter a string for me to analyze: ");
                userString = scan.nextLine();
     
                if(userString == "") System.out.println("\n\nError: Invalid entry.Please try again...");
                else return userString;
            } while (userString == "");
     
            return userString;
        }
    }
     
    class StringAnalyzer {
        public static void main(String[] args) {
            ClrScrn.clrScrn();
            System.out.println("\n\n");
     
            Scanner scan = new Scanner(System.in);
     
            Input userInput = new Input();
     
            do {
                String userString = userInput.getString();
                int stringLength = userString.length();
     
                Analysis Analyzer = new Analysis();
                int vowelNum = Analyzer.vowelCounter(userString, stringLength);
     
     
                System.out.println("String:   " + userString);
                System.out.println("Length:   " + stringLength);
                System.out.println("Vowels:   " + vowelNum + "\n");
     
                System.out.print("Would you like to run the analyzer again (y/n): ");
                String repeat = scan.next();
     
                if(repeat == "y") break;
            } while(true);
     
            System.out.println("\n\n");
        }
    }

    Error:
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    	at java.lang.String.charAt(String.java:658)
    	at Analysis.vowelCounter(StringAnalyzer.java:26)
    	at StringAnalyzer.main(StringAnalyzer.java:69)

    P.S. I entered "test" in the above trial


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: StringIndexOutOfBounds exception

    for(int stringCounter = 0; stringCounter <= stringLength; stringCounter++) {

    That says to loop while (and including) the length of the String. The length of the String is not a valid index. Indexes go from 0 to the length - 1 (inclusively). Instead of looping while stringcounter is less than or equal to stringLength, try looping while stringCounter is less than stringLength (no equals to).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. The Following User Says Thank You to aussiemcgr For This Useful Post:

    NuclearCherry (November 12th, 2013)

  4. #3
    Junior Member
    Join Date
    Nov 2013
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: StringIndexOutOfBounds exception

    Quote Originally Posted by aussiemcgr View Post
    Instead of looping while stringcounter is less than or equal to stringLength, try looping while stringCounter is less than stringLength (no equals to).
    Awesome, thanks! That fixed my issue there. However, I've run into another issue with my code that I need a bit of help with if anybody can provide it. I've been having a recurring issue with my code when I try to prompt the user if they would like to run the program again without terminating. What I've been trying to do is make it so that when they enter "n" (located at the end of the code, it's one of the last lines in the main method) the program would terminate. If they enter "y" then the program would start from the beginning. If they enter anything other than y or n, the program would output an error message telling them so, and it would re-prompt for an appropriate response.

    I've edited the last bit of the code, so now I'm trying to do what I just mentioned by breaking to a label located at the start of the first do/while loop (so that when it breaks to the label, the program should just bypass the loop and end the program, right?), but I can't seem to get it to work. I'm not sure if I'm using one of the pieces wrong, or if there's just something wrong with my code. I've posted the edited main method below, since that seems to be the only part that is messed up (and the only part that I changed, except for what Aussiemcgr mentioned above)

    class StringAnalyzer {
        public static void main(String[] args) {
            ClrScrn.clrScrn();
            System.out.println("\n\n");
     
            Scanner scan = new Scanner(System.in);
     
            Input userInput = new Input();
     
            MainLoop:
            do {
                String userString = userInput.getString();
                int stringLength = userString.length();
     
                Analysis Analyzer = new Analysis();
                int vowelNum = Analyzer.vowelCounter(userString, stringLength);
     
     
                System.out.println("String:   " + userString);
                System.out.println("Length:   " + stringLength);
                System.out.println("Vowels:   " + vowelNum + "\n");
     
                String repeat;
     
                do {
                    System.out.print("Would you like to run the analyzer again (y/n): ");
                    repeat = scan.next();
     
                    if(repeat == "n") break MainLoop;
                    else if(repeat == "y") break;
     
                    System.out.println("Error: Invalid Entry. Please try again.\n");
                } while(true);
            } while(true);
     
            System.out.println("\n\n");
        }
    }

    I also included a test run of the program to show what I'm talking about when I say that it doesn't end.
    Please enter a string for me to analyze: test
    String:   test
    Length:   4
    Vowels:   1
     
    Would you like to run the analyzer again (y/n): n
    Error: Invalid Entry. Please try again.
     
    Would you like to run the analyzer again (y/n): y
    Error: Invalid Entry. Please try again.

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: StringIndexOutOfBounds exception

    Use the equals() method to compare Strings, not the == operator.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 4
    Last Post: February 20th, 2013, 10:01 AM
  2. Replies: 1
    Last Post: February 6th, 2013, 11:21 AM
  3. I'm getting a random, stringindexoutofbounds exception
    By Programming_Hobbyist in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 31st, 2012, 11:48 AM
  4. Replies: 5
    Last Post: September 5th, 2011, 10:31 AM
  5. StringIndexOutOfBounds Exception
    By adamLovesCS in forum What's Wrong With My Code?
    Replies: 4
    Last Post: July 16th, 2011, 06:52 AM