`
luhantu
  • 浏览: 201418 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java String is number

    博客分类:
  • Java
阅读更多

ibcommons-lang-java 包中提供了一个类NumberUtils.java的isNumber()方法来验证一个string是否是numberic。现在分享出来。

public static boolean isNumber(String str) {
        if (StringUtils.isEmptyString(str)) {
            return false;
       }
        char[] chars = str.toCharArray();
        int sz = chars.length;
        boolean hasExp = false;
        boolean hasDecPoint = false;
        boolean allowSigns = false;
        boolean foundDigit = false;
        // deal with any possible sign up front
        int start = (chars[0] == '-') ? 1 : 0;
        if (sz > start + 1) {
            if (chars[start] == '0' && chars[start + 1] == 'x') {
                int i = start + 2;
                if (i == sz) {
                    return false; // str == "0x"
                }
                // checking hex (it can't be anything else)
                for (; i < chars.length; i++) {
                    if ((chars[i] < '0' || chars[i] > '9')
                        && (chars[i] < 'a' || chars[i] > 'f')
                        && (chars[i] < 'A' || chars[i] > 'F')) {
                        return false;
                    }
                }
                return true;
            }
        }
        sz--; // don't want to loop to the last char, check it afterwords
              // for type qualifiers
        int i = start;
        // loop to the next to last char or to the last char if we need another digit to
        // make a valid number (e.g. chars[0..5] = "1234E")
        while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
            if (chars[i] >= '0' && chars[i] <= '9') {
                foundDigit = true;
                allowSigns = false;

            } else if (chars[i] == '.') {
                if (hasDecPoint || hasExp) {
                    // two decimal points or dec in exponent   
                    return false;
                }
                hasDecPoint = true;
            } else if (chars[i] == 'e' || chars[i] == 'E') {
                // we've already taken care of hex.
                if (hasExp) {
                    // two E's
                    return false;
                }
                if (!foundDigit) {
                    return false;
                }
                hasExp = true;
                allowSigns = true;
            } else if (chars[i] == '+' || chars[i] == '-') {
                if (!allowSigns) {
                    return false;
                }
                allowSigns = false;
                foundDigit = false; // we need a digit after the E
            } else {
                return false;
            }
            i++;
        }
        if (i < chars.length) {
            if (chars[i] >= '0' && chars[i] <= '9') {
                // no type qualifier, OK
                return true;
            }
            if (chars[i] == 'e' || chars[i] == 'E') {
                // can't have an E at the last byte
                return false;
            }
            if (chars[i] == '.') {
                if (hasDecPoint || hasExp) {
                    // two decimal points or dec in exponent
                    return false;
                }
                // single trailing decimal point after non-exponent is ok
                return foundDigit;
            }
            if (!allowSigns
                && (chars[i] == 'd'
                    || chars[i] == 'D'
                    || chars[i] == 'f'
                    || chars[i] == 'F')) {
                return foundDigit;
            }
            if (chars[i] == 'l'
                || chars[i] == 'L') {
                // not allowing L with an exponent
                return foundDigit && !hasExp;
            }
            // last character is illegal
            return false;
       }
        // allowSigns is true iff the val ends in 'E'
        // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
       return !allowSigns && foundDigit;
    }

 

分享到:
评论

相关推荐

    JavaScript中string转换成number介绍

    在JavaScript中,将字符串(string)转换为数字(number)是常见的数据类型转换操作。有三种主要的方法可以实现这一目标:Number()函数、parseInt()函数和parseFloat()函数。下面将详细介绍这三种方法及其特点。 1. ...

    java程序的编码通过样例test。java(附执行程序)

    System.out.println("Number is negative or zero."); } ``` 循环: ```java for (int i = 0; i ; i++) { System.out.println(i); } ``` 以及方法调用: ```java public static void printHello() { System.out....

    String与int相互转换

    String str = "The number is " + num; ``` 3. 源码解析: Integer.parseInt()和Integer.toString()这两个方法的源码值得深入研究。parseInt()会通过解析字符数组来计算整数值,而toString()则会根据整数值生成...

    回文数 java

    java回文数源码 实验作业 能用 预览:import java.util.Scanner; public class Ahuiwen { public static void main(String args[]) { System.out.println("输入你要判断的字符串:"+"\n"); Scanner in=...

    常见数据结构的Java实现

    list.add("is"); list.add("a"); int number=list.size(); System.out.println("现在链表中有"+number+ "个节点:"); for(int i=0;i&lt;number;i++) { String temp=(String)list.get(i); System.out.println("第...

    java获取字符串内全部数字

    String inputString = "Hello, my age is 25 and phone number is 123456789."; String regex = "\\d+"; // 正则表达式,表示一个或多个连续的数字 Pattern pattern = Pattern.compile(regex); // 编译正则...

    ACM的一道题--Parenthesize the string

    Find an efficient algorithm that examines a string of these symbols, say bbbbac, and decides whether or not it is possible to parenthesize the string in such a way that the value of the resulting ...

    java实验报告:实验六.doc

    实验六: 给定一数据库test,数据库任选。给定表student,字段任意,实现对该表的增、删、改 、查操作。... } public void setphonenumber(String phonenumber) { this.phonenumber=phonenumber; } public Integ

    Coding Interview In Java

    14 Two Sum II Input array is sorted 49 15 Two Sum III Data structure design 51 16 3Sum 53 17 4Sum 55 18 3Sum Closest 57 19 String to Integer (atoi) 59 20 Merge Sorted Array 61 ... ... 231 Counting ...

    java基础编程教程

    System.out.println("Number is positive."); } else if (num ) { System.out.println("Number is negative."); } else { System.out.println("Number is zero."); } for (int i = 1; i ; i++) { System.out....

    计科2022-java复习

    例如,`$number`是合法的标识符,而`super`是Java的关键字,`3number`和`#number`则因为首字符非字母、下划线或美元符号而不合法。 1.2 **关键字** 关键字在Java中具有特殊含义,如`final`、`package`、`abstract`...

    常用正则表达式HTML,JAVA合集

    String phoneNumber = "1234567890"; String regex = "^\\d{10}$"; // 匹配10位数字的电话号码 Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(phoneNumber); boolean isValid ...

    java5与as3语法的区别

    - ActionScript 3 提供了 `is` 运算符,如 `if (myvar is String) {...}`,以及 `as` 运算符,用于类型转换,如 `var orderIdn:number = orderId as Number;` 12. 基本数据类型: - Java 5 包括 byte, int, long,...

    java的一些简单的例程

    System.out.println("Number is negative or zero."); } ``` 此外,Java支持函数(function)的定义和调用,这使得代码可重用性增强。比如,计算两个数的和的函数: ```java public int addNumbers(int a, int b)...

    Java高新技术_java5的枚举的基本应用

    public static void main(String[] args) { Color color = Color.RED; switch (color) { case RED: System.out.println("The color is Red"); break; case GREEN: System.out.println("The color is Green")...

    java实现验证银行卡的正确性

    通常,这样的类会包含一个方法,如`isValid(String cardNumber)`,该方法接收一个银行卡号字符串作为参数,然后执行Luhn算法验证。 以下是Luhn算法的步骤: 1. **反转数字顺序**:从右到左读取银行卡号,将偶数...

    简单谈谈Java中String类型的参数传递问题

    在示例中,如果用int类型的`number`替换`String`,那么`changeNumber`方法内的修改不会影响到`main`方法中的`number`。 然而,对于引用类型(如Object的子类,包括String),情况有所不同。尽管Java没有指针,但它...

    java 分割文件 将大文件分割成小文件

    String fileNamePart = "part-" + partNumber + ".dat"; while ((bytesRead = fis.read(buffer)) != -1) { if (currentFileSize + bytesRead &gt; blockSizeInBytes) { // 创建新的部分文件 fos.close(); part...

    Java程序检查一个数字是否是霓虹灯数字.docx

    // Java Program to Check If a Number is Neon number or not // Importing java input/output library import java.io.*; class GFG { // Method to check whether number is neon or not // Boolean type ...

    JAVA调用梦网云通讯平台API实现短信发送

    String msg = "Hello, this is a test message!"; // 计算签名 String sig = calculateSignature(appKey, secret, to, msg); URL url = new URL("https://api.mengwang.com/sms/send"); HttpURLConnection ...

Global site tag (gtag.js) - Google Analytics