【问题标题】:Counting the number of characters that are not in an array计算不在数组中的字符数
【发布时间】:2017-03-24 00:08:34
【问题描述】:

在这种方法中,我计算数据文件中的字符类型。它成功计算了字符 A-Z(大写)、a-z(小写)和任何数字的数量,如果除了已经计算的字符之外还有任何其他类型的字符,我还需要它来计算。我尝试过的所有内容都计算了所有字符,没有字符,或者只有少数几个。

谢谢

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

【问题讨论】:

标签: arrays if-statement char


【解决方案1】:

你应该检查他们的ascii值会更容易,使用(int) my_char

并检查它的值是否在 0-47、58-64 或 91-127 之间。请参阅此表了解原因:ASCII VALUES

这基本上是你已经在做的,说if(char &gt;= a &amp;&amp; char &lt;= z) 下一个代码应该足以解决你的问题。

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

【讨论】:

  • 我将如何使用 ASCII 值?如果我刚刚输入 (char = 30) 它不会只查找 0 到 30 之间的数字吗?
  • 是的,但您不会比较 char,您将与它的 ASCII 值进行比较(是的,它也是您的 char)我会在我的答案中添加代码
猜你喜欢
  • 1970-01-01
  • 2015-08-25
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2020-05-06
  • 1970-01-01
相关资源
最近更新 更多