Java ParseInt() - 用前导零捕获字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28344775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:25:27  来源:igfitidea点击:

Java ParseInt() - Catching Strings with a leading zero

javazeroparseintleading-zero

提问by s-low

Java's ParseIntmethod will happily parse decimal values supplied with a leading zero without throwing an exception, stripping the zero:

Java 的ParseInt方法将很高兴地解析带有前导零的十进制值,而不会抛出异常,剥离零:

int value = Integer.parseInt("050", 10);

will result in the integer value 50.

将导致整数值 50。

But, I have an application requiring a string such as this to be rejected as invalid input. My solution to the problem so far has been to convert the parsed integer back to a string, and compare the lengths of original/parsed strings to see if any character has been stripped, eg:

但是,我有一个应用程序需要这样的字符串作为无效输入被拒绝。到目前为止,我对问题的解决方案是将解析的整数转换回字符串,并比较原始/解析字符串的长度以查看是否有任何字符被剥离,例如:

String original = "050";
value  = Integer.parseInt( "050", 10);
String parsed = Integer.toString(value);
if (original.length() != parsed.length()) {
    System.exit(1);
}

Which works fine, but feels a little hacky. Are there better ways of detecting and handling a leading zero?

这工作正常,但感觉有点hacky。有没有更好的方法来检测和处理前导零?

回答by Eran

Check if the first character is 0 :

检查第一个字符是否为 0 :

if (original.charAt(0)=='0')

or

或者

if (original.startsWith("0"))

If the String starts with a 0, you don't want to call parseIntat all.

如果字符串以 0 开头,则您根本不想调用parseInt

I think that comparing a single character is more efficient than using regular expressions.

我认为比较单个字符比使用正则表达式更有效。

回答by SomeJavaGuy

you could work with regex and check if it has a leading 0

您可以使用正则表达式并检查它是否有前导 0

you could just write

你可以写

After seeing your comment about leading whitespaces beeing allowed you could use:

在看到您关于允许使用领先空格的评论后,您可以使用:

if(original.matches(".\s0.*[1-9]")) // Wrong number with leading zeros

This way a 00000 would still be a zero, if it′s valid

这样 00000 仍然是零,如果它是有效的

回答by 1Darco1

As you get a string input you can use the method String.charAt(int)to check for explicit characters. However, when you are just using input.charAt(0)the user could avoid the leading zero with a space.

当您获得字符串输入时,您可以使用该方法String.charAt(int)来检查显式字符。但是,当您只是使用时input.charAt(0),用户可以避免使用空格的前导零。

What I would suggest to do:

我建议做的事情:

String decimalChars = "123456789";

boolean reject = true, hasZeros = false;
for (int i = 0; i < input.length; i++) {
    if (input.charAt(i) == '0') { // or other chars you don't want
        hasZeros = true;
        reject = false;
    } else if (decimalChars.contains(input.charAt(i)) {
           if (hasZeros) {
               reject = true;
            } else {
                reject = false;
            }
            break;
        }
    }
}

Using that you can do whatever you want to reject wrong inputs by checking reject. The code will break when it finds a character which is in the decimalChars array. rejectwill be true if it found a zero before, otherwise it'll be false. This code also allows spaces at the beginning and doesn't reject an input like 0000. Empty strings will be rejected as well, because rejectinitializes with true.

使用它,您可以通过检查reject. 当它找到decimalChars 数组中的字符时,代码将中断。reject如果之前找到零则为真,否则为假。此代码还允许开头有空格,并且不会拒绝像0000. 空字符串也将被拒绝,因为reject初始化为 true。

I hope this helps!

我希望这有帮助!