java - 我想打印用户输入的字符串中元音、辅音、空格、数字和特殊字符的数量
问题描述
我需要打印没有。用户输入的字符串中的元音、辅音、空格、数字和特殊字符。
运行程序后出现以下错误。
输入:输入单词以计算其中的元音和字母
java语言版本15#
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: 25
at java.lang.String.charAt(String.java:658)
at CountAlphabetsInWord.main(CountAlphabetsInWord.java:11)
public class CountAlphabetsInWord {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the word to count Vowels and Alphabets in it");
String word = scanner.nextLine();
scanner.close();
int vowels = 0, consonants = 0, spaces = 0, digits = 0, specialCharacters = 0;
word = word.toLowerCase();
for(int i = 0; i <= word.length(); i++){
char ch = word.charAt(i);
//check if any char is a, e, i, o ,u
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'){
vowels++;
}
else if(ch >= '0' && ch <= '9'){
consonants++;
}
else if(ch == ' '){
spaces++;
}
else if(ch >= 'a' && ch <= 'z'){
digits++;
}
else
specialCharacters++;
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Digits: " + digits);
System.out.println("WhiteSpaces: " + spaces);
System.out.println("Special Characters: " + specialCharacters);
}
} ```
解决方案
考虑使用增强的 for 循环,这样您就不必担心索引越界错误,并且出于类似原因,请使用内置Character
方法:
import java.util.Scanner;
import java.util.Set;
public class AnalyzeStringInput {
private static final Set<Character> VOWELS = Set.of('a', 'e', 'i', 'o', 'u');
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a string:");
String string = scanner.nextLine();
int vowels = 0, consonants = 0, spaces = 0, digits = 0, specialCharacters = 0;
for (Character ch : string.toLowerCase().toCharArray()) {
if (Character.isLetter(ch)) {
if (VOWELS.contains(ch)) {
vowels++;
} else {
consonants++;
}
} else if (Character.isSpaceChar(ch)) {
spaces++;
} else if (Character.isDigit(ch)) {
digits++;
} else {
specialCharacters++;
}
}
System.out.println();
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Spaces: " + spaces);
System.out.println("Digits: " + digits);
System.out.println("Special Characters (anything else): " + specialCharacters);
}
}
示例用法:
Please enter a string:
AbcDeF gHi JkLmnO 1234% ~!56&*()
Vowels: 4
Consonants: 11
Spaces: 5
Digits: 6
Special Characters (anything else): 7
推荐阅读
- flutter - 运行 Gradle 任务 'assembleDebug'... [致命错误] aapt2-3.5.0-5435860.pom:2:1:prolog 中不允许内容
- python - 我可以在python的while循环中使用字符串和整数吗?
- ruby-on-rails - 使用关联模型防止 Rails 查询中的 N+1
- algorithm - 快速排序工作和不工作代码比较
- python - 如何将经过时间添加到列表中
- jquery - PUG+Express+Jquery+bootstrap
- ansible - 如何删除没有任何数据的空白行?
- swift - 符合更指定的协议扩展版本
- php - 使用 PHPUnit 将模拟对象传递给父构造函数时出现 TypeError
- javascript - 时刻时区将UTC更改为默认时区