简体   繁体   中英

code not exiting outer for loop

My code isn't exiting my outer for loop even when I come to the end of my string and I cannot figure out why. From my understanding, my outer loop should stop after the fourth iteration. Instead, it continues and then errors out at String inputString = input.next(); because there is nothing there. Here is my code:

public class Exercise17 {
    public static void main(String[] args) {
        String string = "i think, therefore i am";
        vowelCount(string);     
    }
    public static void vowelCount(String s) {
        Scanner input = new Scanner(s);     
        int[] vowelArray = new int[5];
        int aCount = 0, eCount = 0, iCount = 0, oCount = 0, uCount = 0;
        for(int i = 0; i < s.trim().length() - 1; i++) {
            String inputString = input.next();
            System.out.println(inputString);
            for(int j = 0; j < inputString.length(); j++) {
                char c = inputString.charAt(j);
                System.out.println(c);
                if(c == 'a') {
                    aCount++;                   
                }else if (c == 'e') {
                    eCount++;                   
                }else if (c == 'i') {
                    iCount++;                   
                }else if (c == 'o') {
                    oCount++;                   
                }else if (c == 'u') {
                    uCount++;                   
                }               
            }               
        }
        vowelArray[0] = aCount;
        vowelArray[1] = eCount;
        vowelArray[2] = iCount;
        vowelArray[3] = oCount;
        vowelArray[4] = uCount;
        input.close();
        System.out.println(Arrays.toString(vowelArray));    
    }
}

As an experiment I have tried to get rid of the -1 and make it just i < s.trim().length() as well as changing it to i < s.trim().length() -2, i < s.trim().length() -3, i < s.trim().length() -4, etc., all the way up to -10.

Scanner.next() reads content of the input string word by word (ie "i", "think", "therefore", "i", "am") but you are counting the outer loop letter by letter (with respect to the input string). So the next() call throws an exception when the input string is exhausted, after the fifth iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM