迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Java >

如何在 Java 中检查一个字符串是否是一个数字

作者:迹忆客 最近更新:2023/05/16 浏览次数:

本教程将介绍在 Java 中如何检查一个字符串是否为数字,并列举了一些示例代码来了解它。

检查数字字符串的方法有好几种,如使用 regex、Double 类、Character 类或 Java 8 函数式方法等。


在 Java 中检查一个字符串是否是数字

如果且仅当字符串包含数字(有效的数字位)时,它才是数字字符串。例如,"123" 是一个有效的数字字符串,而 "123a" 不是一个有效的数字字符串,因为它包含一个字母。

为了检查数字字符串,我们可以使用 String 类的 matched() 方法,该方法以 regex 为参数,并返回一个布尔值 truefalse

public class SimpleTesting {

    public static void main(String[] args) {
        String str = "123";
        boolean isNumeric =  str.matches("[+-]?\\d*(\\.\\d+)?");
        System.out.println(isNumeric);
        str = "121xy";
        isNumeric =  str.matches("[+-]?\\d*(\\.\\d+)?");
        System.out.println(isNumeric);
        str = "0x234";
        isNumeric =  str.matches("[+-]?\\d*(\\.\\d+)?");
        System.out.println(isNumeric);
    }
}

输出:

true
false
false

使用 Java 中的 Character 类检查字符串是否是数字

我们可以使用 Character 类的 isDigit() 方法来检查循环中的每个字符。它返回 truefalse 值。

public class SimpleTesting {

    public static void main(String[] args) {
        String str = "1123";
        boolean isNumeric = true;
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                isNumeric = false;
            }
        }
        System.out.println(isNumeric);
    }
}

输出:

true

在 Java 中使用 Apache 库检查一个字符串是否是一个数字

如果你使用的是 Apache 库,你可以使用 StringUtils 类的 isNumeric() 方法,如果它包含一个数字序列,则返回 true

import org.apache.commons.lang3.StringUtils;

public class SimpleTesting {

    public static void main(String[] args) {
        String str = "1123";
        boolean isNumeric = StringUtils.isNumeric(str);
        System.out.println(isNumeric);
        str = "123xyz";
        isNumeric = StringUtils.isNumeric(str);
        System.out.println(isNumeric);
    }
}

输出:

true
false

使用 Java 中的 Double 类检查一个字符串是否是一个数字

我们可以使用 Double 类的 parseDouble() 方法,将一个字符串转换为 double 并返回一个 double 类型的值。如果它不能被解析,它会抛出一个异常。

public class SimpleTesting {

    public static void main(String[] args) {
        String str = "1123";
        try {
        Double.parseDouble(str);
        System.out.println("It is numerical string");
        }catch(NumberFormatException e) {
            System.out.println("It is not numerical string");
        }
    }
}

输出:

It is not numerical string

在 Java 8 中检查一个字符串是否是一个数字

如果你使用的是 Java 8 或更高版本,那么你可以使用这个例子来检查数字字符串。这里,Character 类的 isDigit() 方法被传递到 allMatch() 作为方法引用。

public class SimpleTesting {

    public static void main(String[] args) {
        String str = "1123";
        boolean isNumeric = str.chars().allMatch( Character::isDigit );
        System.out.println(isNumeric);
        str = "ab234";
        isNumeric = str.chars().allMatch( Character::isDigit );
        System.out.println(isNumeric);
    }
}

输出:

true
false

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

如何从 Pandas 的日期时间列中提取月份和年份

发布时间:2024/04/23 浏览次数:160 分类:Python

我们可以分别使用 dt.year()和 dt.month()方法从 Datetime 列中提取出年和蛾。我们还可以使用 pandas.DatetimeIndex.month 以及 pandas.DatetimeIndex.year 和 strftime()方法提取年份和月份。

如何获取 Pandas DataFrame 的行数

发布时间:2024/04/23 浏览次数:71 分类:Python

本教程介绍如何通过使用 shape,len()来获取 Pandas DataFrame 的行数,以及有多少行元素满足条件。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便