有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用for循环的java ASCII字符范围

如何涵盖所有小写字母a-z&;的范围;大写的A-Z使用for循环?目前我有:

public static boolean isJavaIdentifierStart (char c) {

  if (c == 'a') { //how do I cover the range of all lowercase letters with a for loop?
    return true;
    } if (c=='Z') { //how do I cover all uppercase letters with a for loop?
      return true;
    } else if (c == '_') {
      return true;
    } else if (c == '$') {
      return true;
    } else
      return false;
  }        
}

共 (2) 个答案

  1. # 1 楼答案

    很难猜测您想要什么,但您可以使用:

    for(char c = 'a'; c < 'z'; c++) {
            System.out.println(c);
    }
    

    编辑您的评论:

    使用以下表达式:(c >= 'a' && c <= 'Z')和类似的范围- 检查

    这是因为char是一个16位无符号整数,因此可以在计算中使用

  2. # 2 楼答案

    使用>=<=运算符测试If要容易得多:

    if( c >= 'a' && c <= 'z' ) { 
       // do something
    }
    

    实际上,您不需要测试该范围内的所有值,只需确保c位于该范围内的某个位置即可。您可以对大写字母执行类似的操作

    事实上,您可以将方法简化为一个return语句:

    public static boolean isJavaIdentifierStart (char c) {
       return (c >= 'a' && c <= 'z') ||
              (c >= 'A' && c <= 'Z') ||
              (c == '_')             || 
              (c == '$');
    }    
    

    但是,我不认为Java标识符可以以$开头,因此您的方法是不正确的