这样做的目标是从用户那里获取一个句子并确定每个元音出现了多少个。除了我不确定如何忽略大写和小写字母但我猜测 equalsIgnoreCase 或 toUpperCase() 之外,大部分工作都已完成。
我还想知道是否有另一种方法可以使用其他一些类来做到这一点String
, StringBuilder
, or Character
。我对编程还是个新手,这一章让我很受不了。
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);
}
}
代码在这里
由于您正在比较原始字符,
Character.toLowerCase(sentence.charAt(i))=='a'
Character.toUpperCase(sentence.charAt(i))=='A'
应该已经是适合您的 Java 案例的最佳方法。
但如果你在字符串上进行比较
sentence.substring(i,i+1).equalsIgnoreCase("a")
会更直接,但阅读起来有点困难。
如果数组或列表中有 String 类型,则调用
s.equalsIgnoreCase("a")
会好很多。请注意,您现在正在与“a”而不是“a”进行比较。
如果您正在使用StringBuilder
/StringBuffer
,你可以打电话toString()
,然后用同样的方法。
sb.toString().substring(i,i+1).equalsIgnoreCase("a");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)