用Java编写如下:主要是采用switch分支语句
/**
*验证输入的字符串是否能构成合法的标识符:字母或下划线开头的字母数字下划线串。
*/
import java.util.Scanner;
public class ValidateIdentifier
{
public static final int ERROR = -1; //错误状态
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("请输入待校验的字符串:");
String input = sc.next();
if(validate(input))
{
System.out.println("合法的标识符!");
}
else
{
System.out.println("非法的标识符!");
}
}
//验证输入的字符串是否能构成合法的标识符:字母或下划线开头的字母数字下划线串。
public static boolean validate(String input)
{
int state = 0; //初始状态0
int index = 0; //字符串下标
if(input == null || "".equals(input)) //非空校验
{
return false;
}
int len = input.length();
while(index < len)
{
char ch = input.charAt(index);
switch(state)
{
case 0:
if(ch == '_' || ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'z')))
{
state = 1;
}
else
{
state = ERROR;
}
break;
case 1:
if(ch == '_' || ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'z'))
|| (ch >= '0' && ch <= '9'))
{
state = 1;
}
else
{
state = ERROR;
}
break;
case ERROR:
return false;
}
index++;
}
return (state == 1); //终止状态为1,此时输入构成合法的标识符。
}
}