表示數值的字串(Java實現)

來源:互聯網
上載者:User

標籤:==   數組   開頭   科學   div   str   logs   bsp   小數   

請實現一個函數用來判斷字串是否表示數值(包括整數和小數)。例如,字串"+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

表示數值的字串(Java實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.