简体   繁体   English

检查用户输入的数字java的格式

[英]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.

相关问题 检查用户是否在文本字段中输入了正确的符号数 - Check user has entered the correct number of symbols in a text field 您如何检查用户输入的是字符串值而不是数字? - How do you check that the user entered a String value instead of a number? 有没有更好的方法来检查用户是否输入了 1-50 之间的数字? - Is there a better way to check if the user entered a number between 1-50? 如何检查用户输入的字符串在Java中是否是某个字母? - How to check if a string entered by a user is a certain letter in Java? java - 如何检查用户是否在java中的字符串中输入了正确的字符? - How to check if a correct character was entered by a user in a string in java? Java-检查用户输入的空白​​值是否失败 - Java - check to see if user entered blank value is failing Java:如何在用户输入数字之前打印相应的字母? - Java: How to print corresponding alphabets till a number entered by user? 如何检查用户是否在 java 中以这种格式插入日期周数和年份的最后两位数字 - How to to check if the user inserted the date in this format week number and last two digits of the year in java 如何检查字符串是否包含Java中的数字格式? - How to check that the string contains the number format in Java? 如何检查JTextField中输入的数字 - How to check JTextField for an entered number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM