Something is wrong with Character Count Java

This program should count the number of characters entered by the user. Where are other other characters such as !, @, $, etc. He should not count #. The following for this is my code:

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); } } 

The problem is the "other" counter. If I log in !, @ And $, it will only count 2 out of 3 characters entered. What's wrong?

+4
source share
7 answers

try the following:

  if (sym >= 'a' && sym <= 'z') { low++; } else if (sym >= 'A' && sym <= 'Z') { up++; } else if (sym >= '0' && sym <= '9') { digit++; } else { other++; } 

or instead of another, you can choose a short set of what might be this symbol:

  } else if ("%!$&".contains(sym)){ other++; } 
+1
source

if you look at the ascii table, you will see that:
'!' = 33
'=' = 61
'@' = 64

the '@' character is not in the range you specify, so it does not count, replace the last condition with:

 if (sym >= '!' && sym <= '@') {...} 
+3
source

Try

 else { other++; } 

instead

 if (sym >= '!' && sym <= '=') { other++; } 

# will not be considered as other because you are already filtering it while .

+1
source

You should use OR (||) in the condition instead of AND (& &)

 if (sym == '!' || sym == '=' || sym == '@' || ...){ other++; } 
0
source

Of course you will catch "everything else"; you just use the else clause. This way you wonโ€™t miss things like you are doing now (because '@' not in the range that you are checking). Do you want this:

 else { other++; } 

where do you have this:

 if (sym >= '!' && sym <= '=') { other++; } 
0
source

You are comparing char based on ASCII value. @ASCII - 64! ASCII - 33 = ASCII - 61

So @ is not between "!" and "=" and does not increment your counter.

0
source

Take a look here and hopefully the answer will introduce it yourself!

http://en.wikipedia.org/wiki/UTF-8

and are you sure that the sequence $, 5, $ will give you the correct answer ?;)

0
source

All Articles