java数字校验_JAVA算法:校验数字(ValidNumber)JAVA版本

更新时间:2023-05-12 10:02:39 阅读: 评论:0

java数字校验_JAVA算法:校验数字(ValidNumber)JAVA版
JAVA算法:校验数字(Valid Number)JAVA版本
验证给定的字符串是否可以解释为⼗进制数字。
例如:
"0" => true
" 0.1 " => true
"abc" => fal
"1 a" => fal
"2e10" => true
" -90e3  " => true
" 1e" => fal
"e3" => fal
" 6e-1" => true
" 99e2.5 " => fal
"53.5e93" => true
" --6 " => fal
"-+3" => fal
"95a54e53" => fal
说明: 我们有意将问题陈述地⽐较模糊。在实现代码之前,你应当事先思考所有可能的情况。这⾥给出⼀份可能存在于有效⼗进制数字中的字符列表:
数字 0-9
指数 - "e"
正/负号 - "+"/"-"
⼩数点 - "."
题⽬分析
题⽬是给定⼀个字符串,判断该字符串是否表⽰的是⼀个数字。
对于给定的字符串,可以使⽤正则表达式进⾏判断:
public boolean isNumber(String s) {
String regex = "\\s*(\\+|-)?(\\d+|(\\d+\\.\\d*)|(\\d*\\.\\d+))(e(\\+|-)?\\d+)?\\s*";
return s.matches(regex);
}
两种不同的正则表达式写法:
im().matches("^[+-]?("
+ "(\\d+(\\.\\d*)?(e[+-]?\\d+)?)"
+ "|((\\.\\d+)(e[+-]?\\d+)?))$");
}
还有⼀种判断⽅法是,使⽤Double类的parDouble()⽅法进⾏转换。
public boolean isNumber(String s) {
// 处理⾮法长度的字符串
if (s == null || s.length() == 0)
return fal;
//设定返回标记,初始值为true
boolean flag = true;
//去空格
s = s.trim();
try {
//使⽤了Double类的parDouble⽅法,将所给的字符串转换为double类型的数double d = Double.parDouble(s);
//判断浮点数,标志位为 f,或者 D
if (s.charAt(s.length() - 1) == 'f' || s.charAt(s.length() - 1) == 'D') {
flag = fal;
}
} catch (Exception e) {
flag = fal;
}
return flag;
}
但是注意:.58e1+9,这种表达⽅法有点异常。
boolean flag=vn.isNumber(".58e1+9");
算法设计
package com.bean.algorithm.basic;
public class ValidNumber {
public boolean isNumber(String s) {
if (s == null || s.length() == 0)
return fal;
int len = s.length();
if (len == 0)
return fal;
int signCount = 0;
boolean hasE = fal;
boolean hasNum = fal;
boolean hasPoint = fal;
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
if (ch >= '0' && ch <= '9') {
hasNum = true;
} el if (ch == 'e' || ch == 'E') {
if (hasE || !hasNum || i == len - 1)
return fal;
hasE = true;
} el if (ch == '.') {
if (hasPoint || hasE)
return fal;
// 0. is true
if (i == len - 1 && !hasNum)
return fal;
hasPoint = true;
} el if (ch == '+' || ch == '-') {
// two signs at most; should not appear in the end if (signCount == 2 || i == len - 1)
return fal;
// sign appears in the middle but no E/e
if (i > 0 && !hasE)
return fal;
signCount++;
} el
return fal;
}

本文发布于:2023-05-12 10:02:39,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/105555.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:字符串   数字   判断   可能   有意   算法   是否   校验
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图