当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Defining isJavaIdentifierStart method

问题描述:

In Java’s Character class, there’s a method named isJavaIdentifierStart(char ch). This method determines if the char argument is permissible as the first character in a Java identifier. A character may start a Java identifier if and only if it is (1) a letter; (2) a currency symbol (i.e., ‘$’); or (3) a connecting punctuation character (i.e., ‘_’ which is the underscore). This method returns true if the character may start a Java identifier; false otherwise.

How do I go about defining my own isJavaIdentifierStart method? So far I have:

public class MyCharacter {

public static boolean isJavaIdentifierStart(char c) {

return true;

}

}

//('a') == true);

//('7') == false);

//('_') == true);

//('$') == true);

//('Z') == true);

//('.') == false);

网友答案:

Since you are beginning to do it with switch/case/default this way:

   public static boolean isJavaIdentifierStart(char c) {
         switch (c) {
         case 'a' : return true;
         //Fill other cases
         default: return false; //default is false
      }        
    }

You can also try some if else blocks:

   public static boolean isJavaIdentifierStart(char c) {
         if(c=='a'){
             return true;
         }else if(c=='_'){
             return true;
         }else if (){//Fill other cases
         }else return false; //default is false
      }        
    }
网友答案:

You could use a regex:

return String.valueOf(c).matches("[a-z$_]");

Add other allowed chars you may need between the character class:

[a-z$£€_.-]

Just be aware the dash character - must be put either at the beginning [-...] or at the end [...-] of the character class.

网友答案:

You can use switch - case to implement, like

public static boolean isJavaIdentifierStart(char c) {

    switch(c)
    {
    case 'a':
    case '_':
    case '$':
    case 'Z': return true;

    case '7':
    case '.': return false;
  }
  return false;
}
网友答案:

Another solution could be to use a Set of allowed characters, and to check if the Set contains the given char:

private static final Set<Character> ALLOWED_JAVA_IDENTIFIER_STARTS;

static {
    Set<Character> allowedJavaIdentifierStarts = new HashSet<Character>();
    for (char c = 'a'; c <= 'z'; c++) {
        allowedJavaIdentifierStarts.add(c);
    }
    allowedJavaIdentifierStarts.addAll(Arrays.asList('$', '£', 'z'));
    allowedJavaIdentifierStarts.addAll(Arrays.asList('.', '-', '_'));
    ALLOWED_JAVA_IDENTIFIER_STARTS = Collections.unmodifiableSet(allowedJavaIdentifierStarts);
}

public static boolean isJavaIdentifierStart(char c) {
    return ALLOWED_JAVA_IDENTIFIER_STARTS.contains(c);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: