使用字符串方法查找和计算字符串中的元音? [英] Use string methods to find and count vowels in a string?

查看:162
本文介绍了使用字符串方法查找和计算字符串中的元音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的家庭作业存在这个问题(我老实说,至少不要试图隐藏它)
而且我在弄清楚如何做这件事时遇到了问题。

I have this problem for homework (I'm being honest, not trying to hide it at least) And I'm having problems figuring out how to do it.

给出以下声明:String phrase =WazzUp? - 谁是第一个??? - IDUNNO;将必要的代码写入
计算字符串中元音的数量,并将相应的消息打印到屏幕上。

Given the following declarations : String phrase = " WazzUp ? - Who's On FIRST ??? - IDUNNO"; Write the necessary code to count the number of vowels in the string and print appropriate message to the screen.

这是我到目前为止的代码:

Here's the code I have so far:

String phrase =  " WazzUp ? - Who's On FIRST ??? - IDUNNO";
int i, length, vowels = 0;
String j;
length = phrase.length();
for (i = 0; i < length; i++)
{

  j = phrase.substring(i, i++);
  System.out.println(j);

  if (j.equalsIgnoreCase("a") == true)
    vowels++;
  else if (j.equalsIgnoreCase("e") == true)
    vowels++;
  else if (j.equalsIgnoreCase("i") == true)
    vowels++;
  else if (j.equalsIgnoreCase("o") == true)
    vowels++;
  else if (j.equalsIgnoreCase("u") == true)
    vowels++;

}
System.out.println("Number of vowels: " + vowels);

但是,当我运行它时,它只会产生一堆空行。任何人都可以帮忙吗?

However, when I run it it just makes a bunch of blank lines. Can anyone help?

推荐答案

phrase.substring(i,i ++); 应该是 phrase.substring(i,i + 1);

i ++ 给出 i 的值,然后加1。正如你现在所做的那样, String j 实际上是 phrase.substring(i,i); ,它总是如此空字符串。

i++ gives the value of i and then adds 1 to it. As you have it right now, String j is effectively phrase.substring(i, i);, which is always the empty string.

您无需在<$的正文中更改 i 的值c $ c> for 循环,因为它已经在中增加(i = 0; i< length; i ++)

You don't need to change the value of i in the body of the for loop since it is already incremented in for (i = 0; i < length; i++).

这篇关于使用字符串方法查找和计算字符串中的元音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆