示例 1: 检查字符串是否为数字
public class Numeric { public static void main(String[] args) { String string = "12345.15"; boolean numeric = true; try { double num = Double.parseDouble(string); } catch (NumberFormatException e) { numeric = false; } if(numeric) System.out.println(string + " is a number"); else System.out.println(string + " is not a number"); } }
输出
12345.15 is a number
在上面的程序中,我们有一个名为
string 的
String 包含要检查的字符串。我们还有一个布尔值
numeric 用于存储最终结果是否为数字。
为了检查
string 是否只包含数字,在 try 块中,我们使用
Double 的
parseDouble() 方法来转换字符串到
Double。
如果它抛出错误(即
NumberFormatException 错误),则意味着
string 不是数字并且
numeric 设置为
<代码>
假
代码>。否则,它是一个数字。
但是,如果要检查是否有多个字符串,则需要将其更改为函数。而且,逻辑基于抛出异常,这可能非常昂贵。
相反,我们可以使用正则表达式的强大功能来检查字符串是否为数字,如下所示。
示例 2: 使用正则表达式(regex)检查字符串是否为数字
public class Numeric { public static void main(String[] args) { String string = "-1234.15"; boolean numeric = true; numeric = string.matches("-?\\d+(\\.\\d+)?"); if(numeric) System.out.println(string + " is a number"); else System.out.println(string + " is not a number"); } }
输出
-1234.15 is a number
在上面的程序中,我们没有使用 try-catch 块,而是使用正则表达式来检查
string 是否为数字。这是使用 String 的
matches() 方法完成的。
在
matches()方法中,
-? 允许零个或多个 - 用于字符串中的负数。
\\d+ 检查字符串必须至少有 1 个或多个数字(\\d)。
(\\.\\d+)? 允许零个或多个给定模式 (\\.\\d+) 其中 \\. 检查字符串是否包含 .(小数点) 如果是,后面应该至少有一个或多个数字\\d+。

