验证java变量名是否合法

java中变量的命名规则:
[1]$,数字,下划线打头;后面可以是数字,字母,下划线;
[2]当然变量自然不能是java中的关键字了(程序中还没做判断)
[3]下面是实现的1.0版本,程序还有需要改进的地方,大家不妨指出啊


package com.img.algorithm;

import java.util.Scanner;

/**
* @author Bruce
* @since 1.0
*
*/
public class CheckJavaName {

public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
String name = sca.next();

String result = checkJavaName(name);
System.out.println(result);
}

/**
* @param variable name of java
* @return true if name is acceptable else return false
*/

private static String checkJavaName(String name)
{
//the variable could not be null or empty and ""
if(name == null || name.length() == 0 || name.trim() == "")
return "Variable of java could not empty , null or \"\"!";

//check the first character
char first = name.charAt(0);
if(!isFirstChar(first))
{
return "The first character of java variable is invalid!";
}

//check the content of the name after the first character
for(int i = 1; i < name.length(); i++){
char c = name.charAt(i);
if((!Character.isLetterOrDigit(c)) && (c != '_'))
return "The remaining content contains invalid characters"; }

return null;

}

/**
* @param A character
* @return true if the char contains in the list else return false
*/
private static boolean isFirstChar(char c)
{
switch(c){
case 'A': return true;
case 'B': return true;
case 'C': return true;
case 'D': return true;
case 'E': return true;
case 'F': return true;
case 'G': return true;
case 'H': return true;
case 'I': return true;
case 'J': return true;
case 'K': return true;
case 'L': return true;
case 'M': return true;
case 'N': return true;
case 'O': return true;
case 'P': return true;
case 'Q': return true;
case 'R': return true;
case 'S': return true;
case 'T': return true;
case 'U': return true;
case 'V': return true;
case 'W': return true;
case 'X': return true;
case 'Y': return true;
case 'Z': return true;
case 'a': return true;
case 'b': return true;
case 'c': return true;
case 'd': return true;
case 'e': return true;
case 'f': return true;
case 'g': return true;
case 'h': return true;
case 'i': return true;
case 'j': return true;
case 'k': return true;
case 'l': return true;
case 'm': return true;
case 'n': return true;
case 'o': return true;
case 'p': return true;
case 'q': return true;
case 'r': return true;
case 's': return true;
case 't': return true;
case 'u': return true;
case 'v': return true;
case 'w': return true;
case 'x': return true;
case 'y': return true;
case 'z': return true;
case '_': return true;
case '$': return true;
}
return false;
}

}



注释:对于函数isFirstChar的实现有没有更加简单的实现呢?这里的时间复杂度是O(1)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值