问题描述
这样做的目的是从用户那里得到一个句子并确定每个元音出现了多少.除了我不确定如何忽略大写和小写字母但我猜是 equalsIgnoreCase 或 toUpperCase().
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().
我还想知道是否有其他方法可以使用其他一些 String
、StringBuilder
或 Character
类.我对编程还是很陌生,这一章让我很生气.
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
A:%d
E:%d
I:%d
O:%d
U:%d",
counterA,counterE,counterI,counterO,counterU);
JOptionPane.showMessageDialog(null, message);
}
}
代码在这里
推荐答案
由于你是在原始字符上进行比较,
Since you are comparing on primitive char,
Character.toLowerCase(sentence.charAt(i))=='a'
Character.toUpperCase(sentence.charAt(i))=='A'
应该已经是您在 Java 中的最佳方式了.
should already be the best way for your case in Java.
但是如果你在 Stirng 上进行比较
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.
如果数组或列表中有 String 类型,则调用
If you have a String type inside an array or list, calling
s.equalsIgnoreCase("a")
会好很多.请注意,您现在是在与a"而不是a"进行比较.
will be much better. Please note that you are now comparing with "a" not 'a'.
如果你使用StringBuilder
/StringBuffer
,你可以调用toString()
,然后使用同样的方法.
If you are using StringBuilder
/StringBuffer
, you can call toString()
, and then use the same method.
sb.toString().substring(i,i+1).equalsIgnoreCase("a");
这篇关于比较时忽略char上的大写和小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!