patternjavaModerate
Finding the number of vowels in a string
Viewed 0 times
numberthevowelsfindingstring
Problem
I'm new to Java and is trying to solve the beginners problem of finding out the number of vowels in a string. I was just wondering if there is any alternatives to any of the steps that can improve efficiency as well as simplicity.
import java.util.Arrays;
import java.util.Scanner;
public class CountVowels{
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
String userInput = sc1.next();
sc1.close();
CountVowels cv1 = new CountVowels();
int numberOfVowels = cv1.countingVowels(userInput);
System.out.println(numberOfVowels);
}
public int countingVowels(String s1){
String lowerCaseString = s1.toLowerCase();
int vowelCount = 0;
for (int i = 0; i = 0){
vowelCount += 1;
}
}
return vowelCount;
}
}Solution
Outline
In this case, instantiating a
As a rule, classes should be named as nouns. A better name for the class would be
Implementation
Your
Specifically, note:
Your
In particular:
In this case, instantiating a
new CountVowels() is overkill. all you need is a function.As a rule, classes should be named as nouns. A better name for the class would be
VowelCounter.public class VowelCounter {
public static int vowelCount(String s) {
…
}
public static void main(String[] args) {
…
System.out.println(vowelCount(userInput));
}
}Implementation
Your
countingVowels() function is fine, but could be simpler.public static int vowelCount(String s) {
int count = 0;
for (char c : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) >= 0) {
count++;
}
}
return count;
}Specifically, note:
- Using an enhanced
forloop is less tedious than a counting loop.
- Avoid boxed types such as
Character, when a primitivecharwill do.
- For such a short array, a binary search is overkill.
Your
main() is also OK, but I would write it this way:public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String userInput = scanner.next();
System.out.println(vowelCount(userInput));
}
}In particular:
- A
ScannerisAutoCloseable, so a try-with-resources block is tidier than callingclose()on it manually.
- There doesn't seem to be much point in the
…1suffix on your variable namessc1,cv1, ands1.
Code Snippets
public class VowelCounter {
public static int vowelCount(String s) {
…
}
public static void main(String[] args) {
…
System.out.println(vowelCount(userInput));
}
}public static int vowelCount(String s) {
int count = 0;
for (char c : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) >= 0) {
count++;
}
}
return count;
}public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String userInput = scanner.next();
System.out.println(vowelCount(userInput));
}
}Context
StackExchange Code Review Q#118001, answer score: 15
Revisions (0)
No revisions yet.