什么是标识符呢:
标识符(identifier)是指用来标识某个实体的一个符号,在不同的应用环境下有不同的含义。在计算机编程语言中,标识符是用户编程时使用的名字,用于给变量、常量、函数、语句块等命名,以建立起名称与使用之间的关系。标识符通常由字母和数字以及其它字符构成。
1.必须以字母(a-z A-Z)、下划线(_)、美元符号($)开头;
2.其余部分可以是字母、下划线、美元符、数字的随意组合;
3.区分大小写,长度不限;例如变量Man和变量MAn代表不同的变量
4.不可以使用Java关键字;如下图中的单词就是java中常见的关键字,不能作为标识符使用
代码思路:1、 根据标识符的命名规则,先判断第一位字符合法
2、 然后在根据正则表达式进行匹配除第一位,后面是否合法
3、在结合异常得简单抛出,以及自定义异常类进行抛出
package class_exit;
import java.util.Scanner;
@SuppressWarnings({"all"})//抑制编译器产生警告信息
public class t3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一串字符串");
String string=scanner.next();
try {
String sso=isStr(string);
System.out.println("你输入的字符串合法,是:"+sso);
}catch (IsString e){
System.out.println(e);
}
}
public static String isStr(String string) throws IsString{//构造判断标识符的方法
String str=string.substring(0,1);
if (!(str.equals("_")||str.matches("^[a-zA-Z]$")))//利用正则表达式匹配开头是不是字母或者下划线
throw new IsString(string);
else if (!(str.matches("[^0-9]$")))//匹配标识符第一位是不是数字
throw new IsString(string);
else if ((string.matches("^[a-z0-9A-Z]$")))//正则匹配全部的数字字母以及下划线
throw new IsString(string);
else
return string;
}
}
class IsString extends Exception{
public IsString(String str) {
super(str+"不可以构成标识符哟!!!");
}
}
以上就是通过Java中的自定义异常判断标识符是否合法,写得不是很好,请给位大佬给我指点迷津,下次改进,谢谢给位大佬。



