编写一个程序,判断一个字符串是否是合法的Java标识符;
//create string import java.util.regex.*; public class Split { public static void main (String[] args) { Pattern pattern = Pattern.compile("[,]"); String[] arrStr = pattern.split("abstract,break,byte,boolean,catch,case,class,char,continue,default,double,do,else,extends,false,final,float,for,finally,if,import,implements,int,interface,instanceof,long,length,native,new,null,package,private,protected,public,return,switch,synchronized,short,static,super,try,true,this,throw,throws,threadsafe,transient,void,while"); int length = arrStr.length; for(int i=0; i<length; ++i) { System.out.print("/"" + arrStr[i] + "/"" + ","); } System.out.println(); } }
import java.util.*; public class RE { public static void main (String[] args) { String[] keyword = new String[] {"abstract","break","byte","boolean","catch","case","class","char","continue","default","double","do","else","extends","false","final","float","for","finally","if","import","implements","int","interface","instanceof","long","length","native","new","null","package","private","protected","public","return","switch","synchronized","short","static","super","try","true","this","throw","throws","threadsafe","transient","void","while"}; Scanner in = new Scanner(System.in); p("Input String:"); String str = in.next(); boolean flag = true; for(int i=0; i<keyword.length; ++i) { if(str.equals(keyword[i])) { flag = false; break; } } if(false == flag) { p("It's NOT a Java identifier!"); } else { String regEx = "[$a-zA-Z][$//w]*"; if(str.matches("[$a-zA-Z][$//w]*")) { p("This is a Java identifier!"); } else { p("It's NOT a Java identifier!"); } } } public static void p (String s) { System.out.println(s); } }