我的for循环迭代两次

时间:2017-08-07 23:38:42

标签: java

我正在尝试创建一个计算句子中元音数量的程序,但由于某种原因,我的for循环继续迭代2(通过在每次迭代期间打印出i的值来计算出来)。怎么了?

 //input
    Scanner input = new Scanner(System.in);
    String sentence;
    //prompt
    System.out.print("Type a sentence. \nThe number of vowels will be counted.");
    sentence = input.nextLine();
    //vowel check
    int charcount = 0;
    String temp;
    for(int i = 0; i < sentence.length(); i++)
    {
      temp = sentence.substring(i, i++);
      if (temp.equalsIgnoreCase("a") == true) 
        charcount ++;
      else if (temp.equalsIgnoreCase("e") == true) 
        charcount ++;
      else if (temp.equalsIgnoreCase("i") == true) 
        charcount ++;
      else if (temp.equalsIgnoreCase("o") == true) 
        charcount ++;
      else if (temp.equalsIgnoreCase("u") == true) 
        charcount ++;

      }

     System.out.print("There are " + charcount + " vowels in your sentence.");
}
}

4 个答案:

答案 0 :(得分:5)

在你的for循环定义中有两次递增i,在sentence.substring

中递归一次

每次放i++变量i都会增加1,无论它是在for循环的定义中还是在循环的另一部分中。

for(int i = 0; i < sentence.length(); i++)
{
      temp = sentence.substring(i, i+1);
      if (temp.equalsIgnoreCase("a") == true) 
        charcount ++;
      else if (temp.equalsIgnoreCase("e") == true) 
        charcount ++;
      else if (temp.equalsIgnoreCase("i") == true) 
        charcount ++;
      else if (temp.equalsIgnoreCase("o") == true) 
        charcount ++;
      else if (temp.equalsIgnoreCase("u") == true) 
        charcount ++;

}

应该工作。

另外,如果我错了,那么比我更熟悉java的人可以纠正我,但是temp.equalsIgnoreCase()会返回一个布尔值,所以你不需要做== True ,你可以写else if (temp.equalsIgnoreCase("u"))

补充:根据Scary Wombat的评论,你可以更加简化这一点,因为:

for(int i = 0; i < sentence.length(); i++)
{
      temp = sentence.substring(i, i+1);
      if (temp.equalsIgnoreCase("a") || temp.equalsIgnoreCase("e") ||
          temp.equalsIgnoreCase("i") || temp.equalsIgnoreCase("o") ||
          temp.equalsIgnoreCase("u")) 
             charcount ++;
}

答案 1 :(得分:5)

将此行更改为:

temp = sentence.substring(i, i+1);

如果您执行i++,则会增加i的值。

i ++相当于i = i + 1;

答案 2 :(得分:1)

你有两个i ++实例。每个相当于i = i + 1。你可能希望你的第二个是(i + 1)而不是i ++。

答案 3 :(得分:1)

我建议你不要使用substring方法,因为它会从原始字符串中创建一个新字符串。

来自文档:

String  substring(int beginIndex)
Returns a new string that is a substring of this string.

而是使用charAt方法返回指定索引处的字符值。

您还可以使用带有元音的string并在其上调用indexOf方法来清除实现,以测试相关字符是否为元音。以下是一个例子:

String vowels = "aeiou";

sentence = sentence.toLowerCase();
for (int i = 0; i < sentence.length(); i++) {
    char letter = sentence.charAt(i);

    if (vowels.indexOf(letter) > -1) {
        charCount++;
    }
}