Valid Number,判断是否为合法数字
2024-08-24 22:07:00
问题描述:
Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
public boolean isNumber(String s)
{
s = s.trim();
if (s.length() == 0) return false;
boolean hasE = false;
boolean hasDot = false;
boolean hasNumber = false; for (int i = 0; i < s.length(); i++)
{
// e cannot be the first character
if (i == 0 && s.charAt(i) == 'e') return false;
if (s.charAt(i) == 'e') {
// e cannot be replicated nor placed before number
if (hasE == true || hasNumber == false) {
return false;
} else {
hasE = true;
}
} if (s.charAt(i) == '.') {
// '.' cannot be replicated nor placed after 'e'
if (hasDot == true || hasE == true) {
return false;
} else {
hasDot = true;
}
}
// the sign can be placed at the beginning or after 'e'
if (i != 0 && s.charAt(i - 1) != 'e' && (s.charAt(i) == '+' || s.charAt(i) == '-')) return false; // no other chacraters except '+', '-', '.', and 'e'
if ((s.charAt(i) > '9' || s.charAt(i) < '0') && s.charAt(i) != '+' && s.charAt(i) != '-' && s.charAt(i) != '.' && s.charAt(i) != 'e')
return false; // check whether numbers are included.
if (s.charAt(i) <= '9' && s.charAt(i) >= '0')
{
hasNumber = true;
}
}
// '+', '-', and 'e' cannot be the last character
if (s.charAt(s.length() - 1) == '-' || s.charAt(s.length() - 1) == '+' || s.charAt(s.length() - 1) == 'e') return false; return hasNumber;
}
}
最新文章
- C# MVC绑定 List<;DapperRow>;到bootstrap-table列表
- Excel with COM
- leetcode 70
- php输出utf-8格式
- windows ssh RPi 2B
- C++拾遗(三)关于复合类型
- 用MySQL创建数据库和数据库表
- Unity5 游戏小实例(方块男去打架吧)
- PHP获取客户端操作系统,浏览器,语言,IP,IP归属地等
- 用OpenSSL生成自签名证书在IIS上搭建Https站点(用于iOS的https访问)
- 关于Laravel中的artisan命令
- 如何快速高效地完成一个Android项目?
- 小爬新浪新闻AFCCL
- html试题
- Bootstrap3 代码-程序输出
- [asp.net core 源码分析] 01 - Session
- Var的用法解析
- vue_mint-ui
- SQL语言基础学习
- apache安装及相应配置
热门文章
- vmware key
- nvm-windows 手动安装 nvm use 无效 &#39;node&#39; 不是内部或外部命令,也不是可运行的程序
- Go &; SQLite on Windows
- ORA-08002: sequence TESTTABLE1_ID_SEQ.CURRVAL is not yet defined in this session (未完全解决)
- PHP中Trait详解及其应用
- Python元组组成的列表转化为字典
- 全球第一张中文网络协议分析图——By 成都科来软件
- oradebug工具使用(转载)
- Win10 IIS 安装.net 4.5
- 从零到一创建ionic移动app:应用anjularjs编写ionic项目