【发布时间】:2020-10-12 19:42:53
【问题描述】:
- 编写一个 Java 程序,该程序接受输入字符串并确定辅音、元音(不包括“y”)、标点符号(“.”、“,”、“;”、“!”、“?”)的数量,和空白字符('\n'、'\t'、'')。以合理的清晰度将结果打印到控制台。
import java.util.Scanner;
public class a {
public static void main(String[] args) {
System.out.print("Enter: ");
Scanner scan = new Scanner(System.in);
String input = scan.next();
int whitespace = 0;
int punctuation = 0;
int consonants = 0;
for (int i = 0; i < input.length(); i++){
char ch= input.charAt(i);
if (i == '.' || i == ',' || i == '!' || i == ';' || i =='?')
punctuation++;
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
consonants++;
else if (i == 'y' || i == 'Y')
consonants--;
else
whitespace++;
}
System.out.println("Consonants: " + consonants);
System.out.println("Punctuation: " + punctuation);
System.out.println("White spaces: " + whitespace);
}
}
Enter: yuuh.
Consonants: 4
Punctuation: 0
White spaces: 1
【问题讨论】:
-
将 {} 用于您的 ifs。
-
好吧,如果你没有一个变量来保存元音的数量,你怎么能期望打印出适当数量的元音呢。
-
为什么找到元音时增加
consonants,找到y时减少consonants?这不是你被要求做的。另外,为什么有时检查字符,有时检查它的索引?
标签: java