0

In this method I am counting the type of characters that are in a data file. It successfully counts the number of character A-Z (Uppercase), a-z (Lowercase), and any digit, I also need it to count if there are any other type of character besides the ones already counted. Everything I have tried has counted all of the characters, none of the characters, or only a select few.

Thanks

public void countChars (){
      String currentWord;
      for(int pass = 0; pass < numberOfTokens; pass++){
         currentWord = words[pass];
         for (int i = 0; i < currentWord.length(); i++){
            char ch = currentWord.charAt(i);
            if (ch >= 'A' && ch <= 'Z'){
               numberOfUpperCase++;
            }
            if (ch >= 'a' && ch <= 'z'){
               numberOfLowerCase++;
            }
            if (ch >= '0' && ch <= '9'){
               numberOfDigits++;
            }
         }       
      }
    }//end of countChars
S. Morrison
  • 49
  • 1
  • 11

1 Answers1

-1

You should check their ascii values it will be easier, use (int) my_char

and check if it's value is between 0-47, 58-64 or 91-127. Refer to this table to understand why: ASCII VALUES

This is basically what you are already doing, by saying if(char >= a && char <= z) The next code should be enough to solve your issue.

    char my_char = '@';
    int ascii_value = (int) my_char;

    System.out.println("ASCII value of " + my_char + " is " + ascii_value);

    if((ascii_value >= 0 && ascii_value <= 47) || (ascii_value >= 58 && ascii_value <= 64) || (ascii_value >= 91 && ascii_value <= 127)){
        System.out.println("Your character is a symbol!");
    }
Alan
  • 361
  • 3
  • 22
  • How would I use the ASCII value? If I just entered (char <= 0 && char >= 30) wouldnt it just look for numbers between 0 ad 30? – S. Morrison Mar 24 '17 at 00:55
  • Yes but you will not compare char, you will compare with it's ASCII value (which yes it is also your char) I'll add code to my answer – Alan Mar 24 '17 at 17:52