How can I make a simple vowel counter method in Java?
Here's my method:
public char[] ReturnAllVowels(String word)
{
for (int i = 0; i < word.length(); i++)
{
if (word.contains("a" || "e" || "i" || "o" || "u"))
{
}
}
}
It says that || cannot be appl开发者_Go百科ied to String class. How can I do this then?
Using regular expressions you can try.
int count = word.replaceAll("[^aeiouAEIOU]","").length();
char ch = word.charAt (i);
if (ch == 'a' || ch=='e') {
}
String regex = "[aeiou]";
Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
int vowelcount = 0;
Matcher m = p.matcher(content);
while (m.find()) {
vowelcount++;
}
System.out.println("Total vowels: " + vowelcount);
You can use Peter's code to get the vowels.
char[] vowels = word.replaceAll("[^aeiouAEIOU]","").toCharArray();
This is the way I did it
public static void main(String[] args) {
// TODO code application logic here
// TODO code application logic here
String s;
//String vowels = a;
Scanner in = new Scanner(System.in);
s = in.nextLine();
for(int i = 0; i<s.length();i++){
char v = s.charAt(i);
if(v=='a' || v=='e' || v=='i' || v=='o' || v=='u' || v=='A' || v=='E' || v=='I' || v=='O' || v=='U'){
System.out.print (v);
}
}
}
Here's what I would have done using Scanner
.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userInput;
int vowelA = 0, vowelE = 0, vowelI = 0, vowelO = 0, vowelU = 0;
System.out.println(welcomeMessage);
userInput = scan.nextLine();
userInput = userInput.toLowerCase();
for(int x = 0; x <= userInput.length() - 1; x++) {
if(userInput.charAt(x) == 97)
vowelA++;
else if(userInput.charAt(x) == 101)
vowelE++;
else if(userInput.charAt(x) == 105)
vowelI++;
else if(userInput.charAt(x) == 111)
vowelO++;
else if(userInput.charAt(x) == 117)
vowelU++;
}
System.out.println("There were " + vowelA + " A's in your sentence.");
System.out.println("There were " + vowelE + " E's in your sentence.");
System.out.println("There were " + vowelI + " I's in your sentence.");
System.out.println("There were " + vowelO + " O's in your sentence.");
System.out.println("There were " + vowelU + " U's in your sentence.");
}
精彩评论