Reputation: 97
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
Upvotes: 2
Views: 14888
Reputation: 15785
Since you are comparing on primitive char,
Character.toLowerCase(sentence.charAt(i))=='a'
Character.toUpperCase(sentence.charAt(i))=='A'
should already be the best way for your case in Java.
But if you are comparing on Stirng
sentence.substring(i,i+1).equalsIgnoreCase("a")
will be more direct , but a little bit harder to read.
If you have a String type inside an array or list, calling
s.equalsIgnoreCase("a")
will be much better. Please note that you are now comparing with "a" not 'a'.
If you are using StringBuilder
/StringBuffer
, you can call toString()
, and then use the same method.
sb.toString().substring(i,i+1).equalsIgnoreCase("a");
Upvotes: 6
Reputation: 26077
Use equalsIgnoreCase
looks like it is more readable than converting both Strings to uppercase
before a comparison. Readability trumps micro-optimization.
below looks more readable
if (myString.toUpperCase().equals(myAnotherString.toUpperCase())) {
or
if (myString.equalsIgnoreCase(myAnotherString))
Upvotes: 0
Reputation: 516
equalsIgnoreCase or toUpperCase() method is the best (and the easiest) option.
Upvotes: 2