java - 用Java解析数字

标签 java scanf

我有一个字符串,我假设它是 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/

相关文章:

java - 为什么我们在实现 Interface 方法时使用 @Override ?它真的重写了方法吗?

java - 如何使用 Apache Jena 在 RDF 文档中编写新节点?

c - 程序不会打印 txt 文件中的所有行

c - 如何读取未知长度的输入字符串?

c - 这个 for 循环会无限运行吗?

c - 将文件中的行保存到新字符串中。 C

java - 堆栈返回对象而不是整数

java - HttpURLConnection : What is the right way to read data from a WebService, 逐字符还是逐行?

java - JavaFX 初始化方法中的 NullPointerException

c - C 中的无限循环 fscanf