[英]Check the format of user entered number java
I want to check whether the user entered double value is in the format XXX.YYY.我想检查用户输入的双精度值是否为 XXX.YYY 格式。 If it is then it would return true otherwise false.如果是,那么它将返回 true 否则返回 false。 I want to know if its possible to do this with decimalFormat class.我想知道是否可以使用 decimalFormat 类来做到这一点。 People have said to use regex, but that is out of scope for me right now.人们说要使用正则表达式,但现在这超出了我的范围。
Pure java string solution:纯java字符串解决方案:
public static boolean isValid(String str) {
if (str == null || str.length() != 7) {
return false;
}
return Character.isDigit(str.charAt(0)) && Character.isDigit(str.charAt(1)) && Character.isDigit(str.charAt(2))
&& str.charAt(3)=='.' &&
Character.isDigit(str.charAt(4)) && Character.isDigit(str.charAt(5)) && Character.isDigit(str.charAt(6));
}
public static void main(String[] args) {
System.out.println(isValid("123.456"));
System.out.println(isValid("12.456"));
System.out.println(isValid("abc.456"));
}
try this尝试这个
String s = new String("123.456"); // suppose it is string from your file
String[] splitted = s.split("\\."); //take the part before and after do in the array , splitted is array of two strings
if(splitted.lenght == 2 && splitted[0].length() == 3 && splitted[1].length() == 3) // then it is in abc.xyz format
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.