Example usage for java.lang NumberFormatException NumberFormatException

List of usage examples for java.lang NumberFormatException NumberFormatException

Introduction

In this page you can find the example usage for java.lang NumberFormatException NumberFormatException.

Prototype

public NumberFormatException(String s) 

Source Link

Document

Constructs a NumberFormatException with the specified detail message.

Usage

From source file:org.simplx.args.MainArgs.java

@SuppressWarnings({ "TypeMayBeWeakened" })
private static NumberFormatException numException(NumberFormatException e, String option) {

    NumberFormatException ne = new NumberFormatException("-" + option + " " + e.getMessage());
    ne.initCause(e);// w  w w  .  ja  va2s. com
    return ne;
}

From source file:net.pms.util.Rational.java

/**
 * Parses the specified {@link String} and returns a {@link BigDecimal}
 * using the specified {@link DecimalFormat}. {@code value} is expected to
 * be without leading or trailing whitespace. If {@code value} is blank,
 * {@code null} will be returned./*www  . j a  v a 2s  .com*/
 *
 * @param value the {@link String} to parse.
 * @param decimalFormat the {@link DecimalFormat} to use when parsing.
 * @return The resulting {@link BigDecimal}.
 * @throws NumberFormatException If {@code value} cannot be parsed.
 */
@Nullable
public static BigDecimal parseBigDecimal(@Nullable String value, @Nullable DecimalFormat decimalFormat) {
    if (StringUtils.isBlank(value)) {
        return null;
    }

    if (decimalFormat != null) {
        decimalFormat.setParseBigDecimal(true);
        try {
            return (BigDecimal) decimalFormat.parseObject(value);
        } catch (ParseException e) {
            throw new NumberFormatException("Unable to parse \"" + value + "\": " + e.getMessage());
        }
    }
    return new BigDecimal(value);
}

From source file:it.unimi.di.big.mg4j.tool.Scan.java

public static int[] parseVirtualDocumentGap(final String[] virtualDocumentGapSpec, final int[] indexedField,
        final DocumentFactory factory) {
    final int[] virtualDocumentGap = new int[indexedField.length];
    int defaultGap = DEFAULT_VIRTUAL_DOCUMENT_GAP;
    IntArrayList indexedFields = IntArrayList.wrap(indexedField);
    for (int i = 0; i < virtualDocumentGapSpec.length; i++)
        if (virtualDocumentGapSpec[i].indexOf(':') == -1)
            try {
                defaultGap = Integer.parseInt(virtualDocumentGapSpec[i]);
                if (defaultGap < 0)
                    throw new NumberFormatException("Gap can't be negative");
            } catch (NumberFormatException e) {
                throw new RuntimeException("Cannot parse gap correctly " + virtualDocumentGapSpec[i], e);
            }//w w  w  .j  a  v  a2s. c  o  m
    for (int i = 0; i < virtualDocumentGap.length; i++)
        virtualDocumentGap[i] = defaultGap;
    for (int i = 0; i < virtualDocumentGapSpec.length; i++) {
        final int split = virtualDocumentGapSpec[i].indexOf(':');
        if (split >= 0) {
            final String fieldName = virtualDocumentGapSpec[i].substring(0, split);
            final int field = factory.fieldIndex(fieldName);
            if (field < 0)
                throw new IllegalArgumentException(
                        "Field " + fieldName + " is not part of factory " + factory.getClass().getName());
            if (!indexedFields.contains(field))
                throw new IllegalArgumentException(
                        "Field " + factory.fieldName(field) + " is not being indexed");
            if (factory.fieldType(field) != DocumentFactory.FieldType.VIRTUAL)
                throw new IllegalArgumentException("Field " + factory.fieldName(field) + " is not virtual");
            try {
                virtualDocumentGap[indexedFields.indexOf(field)] = Integer
                        .parseInt(virtualDocumentGapSpec[i].substring(split + 1));
                if (virtualDocumentGap[indexedFields.indexOf(field)] < 0)
                    throw new NumberFormatException("Gap can't be negative");
            } catch (NumberFormatException e) {
                throw new RuntimeException("Cannot parse gap correctly " + virtualDocumentGapSpec[i], e);
            }
        }
    }
    return virtualDocumentGap;
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

/**
 * Gets the int db result.//www  . j a va2s .co  m
 * 
 * @param instanceName
 *            the instance name
 * @param query
 *            the query
 * @return the int db result
 */
public final Integer getIntDBResult(final String instanceName, final String query) {

    ArrayList<Object> arrList;
    Integer value = null;
    try {
        arrList = getDBTable(instanceName, query);
        if (!(arrList.get(0) instanceof Integer)) {
            throw new NumberFormatException("The value trying to retrive (" + arrList.get(0).toString()
                    + ") is not stored as an interger in the database.");
        }
        value = (Integer) arrList.get(0);
        reportresult(true, "SET DB RESULTS : ", "PASSED", "For Query = " + query);
    } catch (SQLException e) {
        String errorString = e.getMessage();
        reportresult(true, "SET DB RESULTS :", "FAILED", "SQL Error occured" + errorString);
        checkTrue(false, true, "SQL Error occured" + errorString);
    } catch (NullPointerException e) {
        String errorString = e.getMessage();
        reportresult(true, "SET DB RESULTS :", "FAILED", errorString);
        checkTrue(false, false, errorString);
    } catch (Exception e) {
        if (e.getMessage().startsWith("Connection instance unavaliable")) {
            reportresult(true, "SET DB RESULTS :" + instanceName + "", "FAILED",
                    "SET DB RESULTS command : connection (" + instanceName + ") is not created. ");
            checkTrue(false, true,
                    "SET DB RESULTS command : connection (" + instanceName + ") is not created. ");
        } else {
            String errorString = e.getMessage();
            reportresult(true, "SET DB RESULTS :", "FAILED", errorString);
            checkTrue(false, false, errorString);
        }
    }
    return value;
}

From source file:com.clark.func.Functions.java

/**
 * <p>//w  ww . j  av  a  2 s  .c om
 * Turns a string value into a java.lang.Number.
 * </p>
 * 
 * <p>
 * First, the value is examined for a type qualifier on the end (
 * <code>'f','F','d','D','l','L'</code>). If it is found, it starts trying
 * to create successively larger types from the type specified until one is
 * found that can represent the value.
 * </p>
 * 
 * <p>
 * If a type specifier is not found, it will check for a decimal point and
 * then try successively larger types from <code>Integer</code> to
 * <code>BigInteger</code> and from <code>Float</code> to
 * <code>BigDecimal</code>.
 * </p>
 * 
 * <p>
 * If the string starts with <code>0x</code> or <code>-0x</code>, it will be
 * interpreted as a hexadecimal integer. Values with leading <code>0</code>
 * 's will not be interpreted as octal.
 * </p>
 * 
 * <p>
 * Returns <code>null</code> if the string is <code>null</code>.
 * </p>
 * 
 * <p>
 * This method does not trim the input string, i.e., strings with leading or
 * trailing spaces will generate NumberFormatExceptions.
 * </p>
 * 
 * @param str
 *            String containing a number, may be null
 * @return Number created from the string
 * @throws NumberFormatException
 *             if the value cannot be converted
 */
public static Number createNumber(String str) throws NumberFormatException {
    if (str == null) {
        return null;
    }
    if (isBlank(str)) {
        throw new NumberFormatException("A blank string is not a valid number");
    }
    if (str.startsWith("--")) {
        // this is protection for poorness in java.lang.BigDecimal.
        // it accepts this as a legal value, but it does not appear
        // to be in specification of class. OS X Java parses it to
        // a wrong value.
        return null;
    }
    if (str.startsWith("0x") || str.startsWith("-0x")) {
        return createInteger(str);
    }
    char lastChar = str.charAt(str.length() - 1);
    String mant;
    String dec;
    String exp;
    int decPos = str.indexOf('.');
    int expPos = str.indexOf('e') + str.indexOf('E') + 1;

    if (decPos > -1) {

        if (expPos > -1) {
            if (expPos < decPos) {
                throw new NumberFormatException(str + " is not a valid number.");
            }
            dec = str.substring(decPos + 1, expPos);
        } else {
            dec = str.substring(decPos + 1);
        }
        mant = str.substring(0, decPos);
    } else {
        if (expPos > -1) {
            mant = str.substring(0, expPos);
        } else {
            mant = str;
        }
        dec = null;
    }
    if (!Character.isDigit(lastChar) && lastChar != '.') {
        if (expPos > -1 && expPos < str.length() - 1) {
            exp = str.substring(expPos + 1, str.length() - 1);
        } else {
            exp = null;
        }
        // Requesting a specific type..
        String numeric = str.substring(0, str.length() - 1);
        boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
        switch (lastChar) {
        case 'l':
        case 'L':
            if (dec == null && exp == null
                    && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
                try {
                    return createLong(numeric);
                } catch (NumberFormatException nfe) {
                    // Too big for a long
                }
                return createBigInteger(numeric);

            }
            throw new NumberFormatException(str + " is not a valid number.");
        case 'f':
        case 'F':
            try {
                Float f = createFloat(numeric);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    // If it's too big for a float or the float value =
                    // 0
                    // and the string
                    // has non-zeros in it, then float does not have the
                    // precision we want
                    return f;
                }

            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            //$FALL-THROUGH$
        case 'd':
        case 'D':
            try {
                Double d = createDouble(numeric);
                if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            try {
                return createBigDecimal(numeric);
            } catch (NumberFormatException e) {
                // ignore the bad number
            }
            //$FALL-THROUGH$
        default:
            throw new NumberFormatException(str + " is not a valid number.");

        }
    } else {
        // User doesn't have a preference on the return type, so let's start
        // small and go from there...
        if (expPos > -1 && expPos < str.length() - 1) {
            exp = str.substring(expPos + 1, str.length());
        } else {
            exp = null;
        }
        if (dec == null && exp == null) {
            // Must be an int,long,bigint
            try {
                return createInteger(str);
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            try {
                return createLong(str);
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            return createBigInteger(str);

        } else {
            // Must be a float,double,BigDec
            boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
            try {
                Float f = createFloat(str);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    return f;
                }
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }
            try {
                Double d = createDouble(str);
                if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // ignore the bad number
            }

            return createBigDecimal(str);

        }
    }
}

From source file:com.clark.func.Functions.java

/**
 * <p>// w ww  . j  av a  2 s.co  m
 * Convert a <code>String</code> to a <code>BigDecimal</code>.
 * </p>
 * 
 * <p>
 * Returns <code>null</code> if the string is <code>null</code>.
 * </p>
 * 
 * @param str
 *            a <code>String</code> to convert, may be null
 * @return converted <code>BigDecimal</code>
 * @throws NumberFormatException
 *             if the value cannot be converted
 */
public static BigDecimal createBigDecimal(String str) {
    if (str == null) {
        return null;
    }
    // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
    if (isBlank(str)) {
        throw new NumberFormatException("A blank string is not a valid number");
    }
    return new BigDecimal(str);
}