在java中使用数组只计算字母
嗨,我想写一个程序,它将完成以下任务 提示用户输入一串数据 使用String类中的charAt(index)方法访问字符串中的每个字符 分别计算字长的数量 只计算字母(不考虑大小写)并处理空格、数字和标点符号 作为分词符。 显示所有非零长度的字数和长度,以及总字数
例如,让我们说这样一句话:Hello Stack Over Flow
2.4个字母单词 15个字母单词 16个字母单词 5个单词
我有这样的想法:
Scanner input = new Scanner (System.in);
int [] wordCount = new int [50];
int i = 0 ,charCount = 0 , j=0;
int counter=0;
System.out.println("Enter the phrase");
String userInput =input.nextLine().toUpperCase();
for ( i = 0;i < userInput.length(); i++){
char charAt = userInput.charAt(i);
if (charAt >= 'A' && charAt <= 'Z') {
counter++;
}
else{
if(i-j>1){
counter++;
j=1;
}
else{
i=j;
}
wordCount[counter]++;
counter=0;
}
}
wordCount[counter]++;
System.out.println(userInput.length());
}
}
这只算单词总数,但从这一点开始,我就被卡住了
# 1 楼答案
首先,Hello Stack Over Flow是四个单词。其次,我将从否定
a-zA-Z
作为拆分模式开始。然后我会按长度对单词进行排序。接下来,我们可以重复从第二个单词开始的单词,检查大小是否相同,并获得计数。然后显示。比如示例输出(带有您提供的输入)