我有一个字符串,我假设它是 6 位整数的零填充表示,例如:
"001234"
我想将其解析为 Long 对象,但我想检查它的格式是否完全相同;如果长度不是 6、不是零填充等,我想返回错误。
在 C 语言中,我会使用 scanf 的一些变体。 Java 的方式是什么?
最佳答案
if(s.length() != 6)
throw new IllegalArgumentException("Input is not of length 6: " + s);
Pattern allDigits = Pattern.compile( "[0-9]+" );
if(!allDigits.matcher(s).matches())
throw new IllegalArgumentException("Input is not numeric: " + s);
long val = Long.parseLong(s);
关于java - 用Java解析数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14039782/