Extracts an Integer 'argument' from a string with a space in between. - Java java.lang

Java examples for java.lang:String Parse

Description

Extracts an Integer 'argument' from a string with a space in between.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String msg = "java2s.com";
        Integer defaultValue = 2;
        System.out.println(GetIntegerArgument(msg, defaultValue));
    }//from   w ww . j a  v  a2s .com

    /** 
     * Extracts an Integer 'argument' from a string with a space in between.
     * For example, use on "/mycommand 123" to get "123".
     * 
     * @param msg String to parse
     * @param defaultValue Default value if error obtaining
     * @return Resulting Integer
     */
    public static Integer GetIntegerArgument(String msg,
            Integer defaultValue) {
        int idxSpace = msg.indexOf(" ");
        if (idxSpace >= 0) {
            try {
                return Integer.parseInt(msg.substring(idxSpace + 1));
            } catch (Exception exc) {
            }
        }
        return defaultValue;
    }
}

Related Tutorials