该程序应该计算用户输入的字符数。other 是其他字符,例如 !、@、$ 等。它不应该计入 #。以下是我执行此操作的代码:
public class countchars {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
char sym;
int up = 0;
int low = 0;
int digit = 0;
int other = 0;
System.out.print("Enter a character # to quit: ");
sym = input.next().charAt(0);
while (sym != '#') {
System.out.print("Enter a character # to quit: ");
if (sym >= 'a' && sym <= 'z') {
low++;
}
if (sym >= 'A' && sym <= 'Z') {
up++;
}
if (sym >= '0' && sym <= '9') {
digit++;
}
if (sym >= '!' && sym <= '=') {
other++;
}
sym = input.next().charAt(0);
}
System.out.printf("Number of lowercase letters: %d\n", low);
System.out.printf("Number of uppercase letters: %d\n", up);
System.out.printf("Number of digits: %d\n", digit);
System.out.printf("Number of other characters: %d\n", other);
}
}
问题在于“其他”计数器。如果我输入 !、@ 和 $,它只会计算输入的 3 个字符中的 2 个。怎么了?