• 表示数值的字符串(Java实现)


    请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。

     1 public class Demo2 {  
     2 
     3     // 数组下标成员变量  
     4     int index;  
     5   
     6     public boolean isNumeric_2(char[] str) {  
     7         // 输入异常  
     8         if (str == null)  
     9             return false;  
    10         index = 0;  
    11         // 正负号开头  
    12         if (str[index] == '+' || str[index] == '-')  
    13             index++;  
    14         if (index == str.length)  
    15             return false;  
    16         // 设置numeric判断是否为数字  
    17         boolean numeric = true;  
    18         scanDigits(str);  
    19         if (index != str.length) {  
    20             // 小数  
    21             if (str[index] == '.') {  
    22                 index++;  
    23                 scanDigits(str);  
    24                 if (index < str.length && (str[index] == 'e' || str[index] == 'E'))  
    25                     numeric = isExponential(str);  
    26             } else if (str[index] == 'e' || str[index] == 'E')  
    27                 numeric = isExponential(str);  
    28             else  
    29                 // 出现了异常字符  
    30                 numeric = false;  
    31         }  
    32   
    33         return numeric && index == str.length;  
    34     }  
    35   
    36     // 扫描数组,如果当前字符为数字,index++  
    37     private void scanDigits(char[] str) {  
    38         while (index < str.length && str[index] >= '0' && str[index] <= '9')  
    39             index++;  
    40     }  
    41   
    42     // 判断是否为科学计数法表示的数值的结尾部分  
    43     private boolean isExponential(char[] str) {  
    44         if (str[index] != 'e' && str[index] != 'E')  
    45             return false;  
    46         index++;  
    47         if (index == str.length)  
    48             return false;  
    49         if (str[index] == '+' || str[index] == '-')  
    50             index++;  
    51         if (index == str.length)  
    52             return false;  
    53         scanDigits(str);  
    54         // 如果存在特殊字符,index不会为str.length  
    55         return index == str.length ? true : false;  
    56     }  
    57 }  

    转载自:http://blog.csdn.net/zjkc050818/article/details/72818475

  • 相关阅读:
    区块链入门
    上海美食餐厅
    《OD学hadoop》20160910某旅游网项目实战
    《OD学hadoop》20160904某旅游网项目实战
    《OD学hadoop》20160903某旅游网项目实战
    qt5-自定义类
    qt5-Qt Creator使用
    qt5-QPushButton按钮
    qt5-工程文件的介绍--快捷键
    电路分析-电阻
  • 原文地址:https://www.cnblogs.com/2390624885a/p/6953883.html
Copyright © 2020-2023  润新知