Java Integer Create toInt(String value, int defaultValue)

Here you can find the source of toInt(String value, int defaultValue)

Description

Returns the given integer string as an int value.

License

Open Source License

Declaration

public static int toInt(String value, int defaultValue) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010, 2011 Tran Nam Quang.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from  ww w  .  ja va  2s .  c om*/
 *    Tran Nam Quang - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Returns the given integer string as an {@code int} value. Leading and trailing whitespaces are ignored. 
     * If the string cannot be parsed, the given default value is returned. If the string is a number, but greater 
     * than {@code Integer.MAX_VALUE} or less than {@code Integer.MIN_VALUE}, a clamped value is returned.
     */
    public static int toInt(String value, int defaultValue) {
        value = value.trim();
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            if (value.matches("\\d{10,}"))
                return Integer.MAX_VALUE;
            else if (value.matches("-\\d{10,}"))
                return Integer.MIN_VALUE;
        }
        return defaultValue;
    }
}

Related

  1. toInt(String value)
  2. toInt(String value)
  3. toInt(String value, int _default)
  4. toInt(String value, int def)
  5. toInt(String value, int defaultValue)
  6. toInt(String value, int defaultValue)
  7. toInt(String value, int defaultValue)
  8. toInt(String value, Integer defaultValue)
  9. toInt(String value, Integer defaultValue)