简体   繁体   English

Java:For循环不打印最后的迭代

[英]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 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. 因此,该程序打印出5个整数,而不是6个整数。我使用它已有很长时间了,但似乎无法解决这个问题。

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. 出于某种原因,当我发布输入内容时,它会自动向我显示前5个整数,然后我只需要按Enter即可显示最后一个整数。 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. 您正在为案例循环1次,即7次。 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 . 您只需要将i < case i <= case更改为i < case一个问题。 You can use this website for testing your code with std input. 您可以使用该网站通过std输入测试您的代码。 https://ideone.com/Ud3MWt https://ideone.com/Ud3MWt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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