简体   繁体   中英

Java: For loop not printing the last iteration

I am currently trying to make a simple program that will calculate the number of vowels in multiple sentences. The input looks like this:
6
Emily jumped high
Alex did not jump
Phillip hates jumping
The red dragon can fly
Sandwiches are nice
I like the sun

The number indicates how many lines there are. My problem is that when I print out the results, the last line gets ignored. So the program prints out 5 ints, rather than 6. I've been playing around with it for ages and I just can't seem to get my head around the issue.

Scanner in = new Scanner(System.in);
int cases = in.nextInt(); //how many lines there are 
String a; 
int vowels = 0;
int length; //length of a line
char temp;
in.nextLine(); //skips first line of the input, as this declares how many lines there are

for (int i = 0; i <= cases; i++) 
{
    a = in.nextLine();
    length = a.length();
    //System.out.println(a);
    for (int b = 0; b < length; b++)
    {
        temp = a.charAt(b);
        if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
        {
            vowels++;
        }
    }
    System.out.println(vowels);
    vowels=0;
}

For some reason when I posted the input, it would automatically show me the first 5 ints, I then just had to press enter to make the last one show up. So apparently hitting enter is now also one of the skills I've acquired ;)

You have extra step in loop:

for (int i = 0; i <= cases; i++)

The loop you need is:

for (int i = 0; i < cases; i++) 

You are looping for cases+1 times ie 7 times. You should either use

for (int i = 0; i < cases; i++)

or

for (int i = 1; i <= cases; i++)

Otherwise your code will print the expected output.

Your code is work fine. Only one problem you need change i <= case to i < case . You can use this website for testing your code with std input. https://ideone.com/Ud3MWt

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