该程序应该计算用户输入的字符数。其他的是其他字符,如!,@,$等。它不应该算#。以下是我的代码:
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个。怎么了?
答案 0 :(得分:3)
如果您查看ascii表,您会看到:
'!' = 33
'='= 61
'@'= 64
'@'字符不在您指定的范围内,因此不计算,将最后一个条件替换为:
if (sym >= '!' && sym <= '@') {...}
答案 1 :(得分:1)
尝试
else {
other++;
}
而不是
if (sym >= '!' && sym <= '=') {
other++;
}
#
不会被计为other
,因为您已在while
条件下对其进行过滤。
答案 2 :(得分:1)
试试这个:
if (sym >= 'a' && sym <= 'z') {
low++;
} else if (sym >= 'A' && sym <= 'Z') {
up++;
} else if (sym >= '0' && sym <= '9') {
digit++;
} else {
other++;
}
或者代替其他你可以选择该角色的短集:
} else if ("%!$&".contains(sym)){
other++;
}
答案 3 :(得分:0)
你应该在条件而不是AND(&amp;&amp;)
中使用OR(||)if (sym == '!' || sym == '=' || sym == '@' || ...){
other++;
}
答案 4 :(得分:0)
确保你抓住“其他一切”;你只需使用else
子句。这样你就不会错过任何东西,就像你现在正在做的那样(因为'@'
不在你正在检查的范围内)。你想要这个:
else {
other++;
}
你现在有这个:
if (sym >= '!' && sym <= '=') {
other++;
}
答案 5 :(得分:0)
您可以根据ASCII值比较char。 @ASAS是64 ! ASCII是33 = ASCII是61
所以@不在“!”之间和“=”并且不会增加你的计数器。
答案 6 :(得分:0)