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