数值字符串验证问题 [英] Numeric string validation problem

查看:94
本文介绍了数值字符串验证问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是问题的描述:验证给定的字符串是否为数字.

一些例子:
"0" =>真实
"0.1" =>真实
"abc" =>错误
"1个" =>错误
"2e10" =>是


到目前为止,我拥有的算法如下:

The following is a description of the problem : Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true


The algorithm I have so far is the following:

public static boolean isNumber(String s) {

        if(s == null){
            return false;
        }
        s = s.toLowerCase();
        s = s.trim();
        if(s == "e" || s == "." || s == "/"){
            return false;
        }

       char[] myObject = new char[]{'0','1','2','3','4','5','6','7','8','9','.','/','e'};
        char[] myChar = s.toCharArray();

        for (int i = 0; i < myChar.length; i++) {

                int temp = 0;
               while(myChar[i] != myObject[temp])
               {
                   temp++;
                   if(temp == myObject.length){
                       return false;
                   }
               }



       }

        return true;
       }



当我在本地计算机上使用"e"作为输入时,它返回false,这是正确的;但是,当我在LeetCode网站上测试相同的代码时,它返回true.我不知道为什么会这样.谁能帮我吗???这是leetcode网站的副本



When I used "e" as an input in my local machine it returns false which is correct; however, when I test the same code in LeetCode website it returns true. I can not figure out why this is happening. Can anyone help me please??? Here is a copy of leetcode''s website

Input:  "e"
Output: true
Expected:   false

推荐答案

您的算法确实很糟糕,非常多余.此外,这是不正确的.例如,根据您的算法,某些仅包含字符"0"至"9"的字符串始终有效,但如果字符串太长,则不能为有效数字.

您需要一种完全不同的方法.只需使用您的输入字符串调用函数parseDouble:
Your algorithm is really bad, very redundant. Besides, it is incorrect. According to you algorithm, for example, some strings containing only the characters ''0'' to ''9'' is always valid, but it cannot be a a valid number if it is too long.

You need a completely different approach. Simply call the function parseDouble with your input string: http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble%28java.lang.String%29[^].

From the documentation referenced above, you can see that NullPointerException or NumberFormatException can be thrown. Catch them both and return false; if the exception wasn''t caught, return true. On top of it, you may want to add the validation for the range of the parsed number.

But even this code would be redundant. You simply don''t need a validation function in this case (unless you also validated the range or something else); you should better do two things at a time: validate and obtain the numeric value from a string. If you want to wrap it in some function which will show validation result or return a valid numeric value, do it.

—SA


这篇关于数值字符串验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆