问题描述:

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;
}
}

最新文章

  1. C# MVC绑定 List&lt;DapperRow&gt;到bootstrap-table列表
  2. Excel with COM
  3. leetcode 70
  4. php输出utf-8格式
  5. windows ssh RPi 2B
  6. C++拾遗(三)关于复合类型
  7. 用MySQL创建数据库和数据库表
  8. Unity5 游戏小实例(方块男去打架吧)
  9. PHP获取客户端操作系统,浏览器,语言,IP,IP归属地等
  10. 用OpenSSL生成自签名证书在IIS上搭建Https站点(用于iOS的https访问)
  11. 关于Laravel中的artisan命令
  12. 如何快速高效地完成一个Android项目?
  13. 小爬新浪新闻AFCCL
  14. html试题
  15. Bootstrap3 代码-程序输出
  16. [asp.net core 源码分析] 01 - Session
  17. Var的用法解析
  18. vue_mint-ui
  19. SQL语言基础学习
  20. apache安装及相应配置

热门文章

  1. vmware key
  2. nvm-windows 手动安装 nvm use 无效 &#39;node&#39; 不是内部或外部命令,也不是可运行的程序
  3. Go &amp; SQLite on Windows
  4. ORA-08002: sequence TESTTABLE1_ID_SEQ.CURRVAL is not yet defined in this session (未完全解决)
  5. PHP中Trait详解及其应用
  6. Python元组组成的列表转化为字典
  7. 全球第一张中文网络协议分析图——By 成都科来软件
  8. oradebug工具使用(转载)
  9. Win10 IIS 安装.net 4.5
  10. 从零到一创建ionic移动app:应用anjularjs编写ionic项目