The goal of this is to get a sentence from the user and determine how many of each vowel shows up.The majority of this is done except I am not sure how to ignore uppercase and lowercase letters but I am guessing equalsIgnoreCase or toUpperCase().
I'd like to also know if there is another way to do this using some other classes of String
, StringBuilder
, or Character
. I'm still new to programming and this chapter is killing me.
int counterA=0,counterE=0,counterI=0,counterO=0,counterU=0;
String sentence=JOptionPane.showInputDialog("Enter a sentence for vowel count");
for(int i=0;i<sentence.length();i++){
if(sentence.charAt(i)=='a'){
counterA++;}
else if(sentence.charAt(i)=='e'){
counterE++;}
else if(sentence.charAt(i)=='i'){
counterI++;}
else if(sentence.charAt(i)=='o'){
counterO++;}
else if(sentence.charAt(i)=='u'){
counterU++;}
}
String message= String.format("The count for each vowel is \nA:%d\nE:%d\nI:%d\nO:%d\nU:%d",
counterA,counterE,counterI,counterO,counterU);
JOptionPane.showMessageDialog(null, message);
}
}
code here
equalsIgnoreCase or toUpperCase() method is the best (and the easiest) option.
Since you are comparing on primitive char,
should already be the best way for your case in Java.
But if you are comparing on Stirng
will be more direct , but a little bit harder to read.
If you have a String type inside an array or list, calling
will be much better. Please note that you are now comparing with "a" not 'a'.
If you are using
StringBuilder
/StringBuffer
, you can calltoString()
, and then use the same method.Use
equalsIgnoreCase
looks like it is more readable than converting both Strings touppercase
before a comparison. Readability trumps micro-optimization.below looks more readable
or