converts a string to an int if the given String is not convertible -> return defaultValue - Java java.lang

Java examples for java.lang:Math Convert

Description

converts a string to an int if the given String is not convertible -> return defaultValue

Demo Code

/**// w w w .  j ava 2s . co m
 * Project: richContentMediaSearchService
 * ROLE-Project
 * authors: daniel.dahrendorf@im-c.de, julian.weber@im-c.de
 * This software uses the GNU GPL   
 */
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        String intString = "java2s.com";
        int defaultValue = 2;
        System.out.println(convertToInt(intString,defaultValue));
    }
    /**
     * converts a string to an int if the given String is not convertible ->
     * return defaultValue
     * 
     * @param intString
     *            the string to convert
     * @param defaultValue
     *            the default value to return on errors
     * @return the String as an int, or the defaultValue, if the string isn't
     *         convertible
     */
    public static int convertToInt(String intString, int defaultValue) {
        int ret = 0;
        try {
            ret = Integer.parseInt(intString);
        } catch (NumberFormatException e) {
            ret = defaultValue;
        }
        return ret;
    }
    /**
     * converts a string to an int if the given String is not convertible ->
     * return defaultValue
     * @param intString
     * @param defaultValue
     * @param negative negative values allowed?
     * @return
     */
    public static int convertToInt(String intString, int defaultValue,
            boolean negative) {
        int ret = convertToInt(intString, defaultValue);
        if (ret < 0) {
            ret = defaultValue;
        }
        return ret;
    }
    /**
     * converts a string to an int if the given String is not convertible ->
     * return defaultValue
     * @param intString
     * @param defaultValue
     * @param negative negative values allowed
     * @param maxValue maximum value
     * @return
     */
    public static int convertToInt(String intString, int defaultValue,
            boolean negative, int maxValue) {
        int ret = convertToInt(intString, defaultValue, negative);
        if (ret > maxValue) {
            ret = defaultValue;
        }
        return ret;
    }
}

Related Tutorials