Java Integer Create toInt(String numStr, int defaultValue)

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

Description

to Int

License

Apache License

Declaration

public static int toInt(String numStr, int defaultValue) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {

    public static int toInt(String numStr, int defaultValue) {
        try {/*from  w  ww  .  java  2 s . c o  m*/
            return Integer.parseInt(numStr);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    public static Integer parseInt(String str) {
        if (str == null || "".equals(str.trim())) {
            return null;
        }
        str = str.trim();
        boolean negative = str.startsWith("-");
        if (negative) {
            str = str.substring(1);
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch >= '0' && ch <= '9') {
                sb.append(ch);
            } else {
                break;
            }
        }
        if (sb.length() == 0) {
            return null;
        }
        int num = Integer.parseInt(sb.toString());
        if (negative) {
            num = -num;
        }
        return num;
    }
}

Related

  1. toInt(String chars)
  2. toInt(String input, int defaultValue)
  3. toInt(String input, int offset, int length)
  4. toInt(String intValue, int defaultValue)
  5. toInt(String number)
  6. toInt(String param)
  7. toInt(String param)
  8. toInt(String pString)
  9. toInt(String s)