我正在做一个字母计数程序。与使用26种情况不同,是否有办法用一种情况来增加字符串中字母的计数。能简化这个程序吗?
import javax.swing.JOptionPane;
public class CountLetters
{
public static void main(String[] args)
{
{
String str = JOptionPane.showInputDialog("Enter any text.");
int count = 0;
String s = str.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i)==('a')||s.charAt(i)=='b'||s.charAt(i)=='c'||s.charAt(i)=='d'||s.charAt(i)=='e'||s.charAt(i)=='f'||
s.charAt(i)=='g'||s.charAt(i)=='h'||s.charAt(i)=='i'||s.charAt(i)=='j'||s.charAt(i)=='k'||s.charAt(i)=='l'||
s.charAt(i)=='m'||s.charAt(i)=='n'||s.charAt(i)=='o'||s.charAt(i)=='p'||s.charAt(i)=='q'||s.charAt(i)=='r'||
s.charAt(i)=='s'||s.charAt(i)=='t'||s.charAt(i)=='u'||s.charAt(i)=='v'||s.charAt(i)=='w'||s.charAt(i)=='x'||
s.charAt(i)=='y'||s.charAt(i)=='z') {
count++;
}
}
System.out.println("There are " + count + " letters in the string you entered.");
}
}
} 有没有办法简化这个程序,以便只有一个条件,而不是26个条件?
发布于 2014-01-01 23:21:48
只需使用大于和小于运算符:
if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z')发布于 2014-01-01 23:31:26
你甚至不需要循环。
int count = str.replaceAll("[^a-zA-Z]","").length();
System.out.println("There are " + count + " letters in the string you entered.");发布于 2014-01-01 23:23:44
您可以使用Java的字符类:
public String numLetters(String str){
int count=0;
for(int i=0; i<str.length(); i++){
if(Character.isLetter(str.charAt(i))){
count++;
}
}
return count;
}https://stackoverflow.com/questions/20874285
复制相似问题