this is my first post here, so please be forgiving ;).
I would say my Java skills are relatively good, but I wanted to have something more (from time to time I explore some gaps). So I decided to "learn" Java from a book, to have everything covered (I'm using this book: Galileo Computing :: Java ist auch eine Insel –).
There is a chapter about identifiers in Java and I decided to implement a check for validating identifiers. So that's basically what my program does:
/** Diese Klasse validiert einen Bezeichner in Java.
* @author Phillip Kessels
*/
public class Main {
private static String identifier = "checkthis123)("; //This is the string which is checked
private static final String[] keywords = {"abstract" , "continue" , "for" , "new" , "switch" , //an array of all reserved words in java
"assert" , "default" , "if" , "package" , "synchronized"
, "boolean" , "do" , "goto" , "private" , "this" ,
"break" , "double" , "implements" , "protected" , "throw"
, "byte" , "else" , "import" , "public" , "throws" ,
"case" , "enum" , "instanceof" , "return" , "transient"
, "catch" , "extends" , "int" , "short" , "try" ,
"char" , "final" , "interface" , "static" , "void" ,
"class" , "finally" , "long" , "strictfp" , "volatile" ,
"const" , "float" , "native" , "super" , "while"};
public static void main(final String[] args) {
int c = 0;
try { //evaluates the identifier
if (Character.isJavaIdentifierStart(identifier.charAt(0))) {
c++;
}
for (int i = 1; i < identifier.length(); i++) {
if (Character.isJavaIdentifierPart(identifier.charAt(i))) {
c++;
}
}
for (String s : keywords) { //check if identifier is a java keyword
if (s.equals(identifier)){
c = 0;
break;
}
}
}
catch (StringIndexOutOfBoundsException e) { //catches the exception which is thrown, when no String is submitted (better null-check via if-else ?)
System.out.println("Sie haben keinen Bezeichner angegeben, oder der Bezeichner besteht aus keinen Zeichen");
System.exit(1);
}
finally {
if (c == identifier.length()) {
System.out.println("Valider Bezeichner!"); //valid identifier
} else {
System.out.println("Kein valider Bezeichner!"); //no valid identifier
}
}
}
}
I'm using eclipse IDE with checkstyle plugin under Mac OS 10.6.
Any comments are appreciated.


Sign In
Create Account

Back to top









