集册 Java实例教程 使用Java的“严格解析”方法Integer.parseInt和Double.parseDouble可以“严格”解析s。

使用Java的“严格解析”方法Integer.parseInt和Double.parseDouble可以“严格”解析s。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

397
使用Java的“严格解析”方法Integer.parseInt和Double.parseDouble可以“严格”解析s。

/**

 *      Copyright (C) 2008 10gen Inc.

 *  

 *    Licensed under the Apache License, Version 2.0 (the "License");

 *    you may not use this file except in compliance with the License.

 *    You may obtain a copy of the License at

 *  

 *       http://www.apache.org/licenses/LICENSE-2.0

 *  

 *    Unless required by applicable law or agreed to in writing, software

 *    distributed under the License is distributed on an "AS IS" BASIS,

 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 *    See the License for the specific language governing permissions and

 *    limitations under the License.

 */


//package com.nowjava;
//NowJava.com - 时代Java 提供

public class Main {

    public static void main(String[] argv) {

        String s = "nowjava.com";

        System.out.println(parseStrict(s));

    }


    /** Use Java's "strict parsing" methods Integer.parseInt and  Double.parseDouble to parse s "strictly". i.e. if it's neither a double or an integer, fail.

     * @param s the string to convert

     * @return the numeric value

     */

    public static Number parseStrict(String s) {

        s = s.trim();
        /*
        时 代      J a v a   公   众 号 - nowjava.com 提供
        */

        if (s.length() == 0)

            return 0;

        if (s.charAt(0) == '+')

            s = s.substring(1);


        if (s.matches("(\\+|-)?Infinity")) {

            if (s.startsWith("-")) {

                return Double.NEGATIVE_INFINITY;

            } else {

                return Double.POSITIVE_INFINITY;

            }

        } else if (s.indexOf('.') != -1 || s.equals("-0")) {

            return Double.parseDouble(s);

        }

        // parse hex

        else if (s.toLowerCase().indexOf("0x") > -1) {

            int coef = s.charAt(0) == '-' ? -1 : 1;

            if (s.length() > 17)

                throw new RuntimeException(

                        "Can't handle a number this big: " + s);

            // if coef == -1: (coef * -.5 + 2.5) == 3

            // e.g., -0xf00 (start substring at 3)

            // if coef == 1: (coef * -.5 + 2.5) == 2

            // e.g., 0xf00 (start substring at 2)

            if (s.length() > 9)

                return coef

                        * Long.parseLong(

                                s.substring((int) (coef * -.5 + 2.5)), 16);

            return coef

                    * Integer.parseInt(

                            s.substring((int) (coef * -.5 + 2.5)), 16);

        }


        int e = s.toLowerCase().indexOf('e');

        // parse exp

        if (e > 0) {

            double num = Double.parseDouble(s.substring(0, e));

            int exp = Integer.parseInt(s.substring(e + 1));

            return num * Math.pow(10, exp);

        }


        // parse with smallest possible precision

        if (s.length() > 17)

            return Double.parseDouble(s);

        else if (s.length() > 9)

            return Long.parseLong(s);

        return Integer.parseInt(s);

    }


    /** Turns a string into an int and returns a default value if unsuccessful.

     * @param s the string to convert

     * @param d the default value

     * @return the int value

     */

    public static int parseInt(String s, int def) {

        return parseInt(s, def, null, true);

    }


    /** Turns a string into an int and returns a default value if unsuccessful.

     * @param s the string to convert

     * @param d the default value

     * @param lastIdx sets lastIdx[0] to the index of the last digit

     * @param allowNegative if negative numbers are valid

     * @return the int value

     */

    public static int parseInt(String s, int def, final int[] lastIdx,

            final boolean allowNegative) {

        final boolean useLastIdx = lastIdx != null && lastIdx.length > 0;

        if (useLastIdx)

            lastIdx[0] = -1;


        if (s == null)

            return def;


        s = s.trim();

        if (s.length() == 0)

            
展开阅读全文