Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string methods to find and count vowels in a string?

Tags:

java

string

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.

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?

like image 943
xSpartanCx Avatar asked Dec 05 '12 23:12

xSpartanCx


People also ask

How do you count the vowels in a string in python?

Step 1: Take a string from the user and store it in a variable. Step 2: Initialize a count variable to 0. Step 3: Use a for loop to traverse through the characters in the string. Step 4: Use an if statement to check if the character is a vowel or not and increment the count variable if it is a vowel.


1 Answers

phrase.substring(i, i++); should be phrase.substring(i, i + 1);.

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.

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++).

like image 165
irrelephant Avatar answered Sep 20 '22 15:09

irrelephant