Java Integer Create toInt(String string)

Here you can find the source of toInt(String string)

Description

Convert String to an integer.

License

Open Source License

Parameter

Parameter Description
string A String containing an integer.

Return

an int

Declaration

public static int toInt(String string) 

Method Source Code

//package com.java2s;
//  are made available under the terms of the Eclipse Public License v1.0

public class Main {
    /**/*from   w ww.  j av a  2  s . c  o m*/
     * Convert String to an integer. Parses up to the first non-numeric character. If no number is found an IllegalArgumentException is thrown
     * 
     * @param string
     *            A String containing an integer.
     * @return an int
     */
    public static int toInt(String string) {
        int val = 0;
        boolean started = false;
        boolean minus = false;

        for (int i = 0; i < string.length(); i++) {
            char b = string.charAt(i);
            if (b <= ' ') {
                if (started)
                    break;
            } else if (b >= '0' && b <= '9') {
                val = val * 10 + (b - '0');
                started = true;
            } else if (b == '-' && !started) {
                minus = true;
            } else
                break;
        }

        if (started)
            return minus ? (-val) : val;
        throw new NumberFormatException(string);
    }
}

Related

  1. toInt(String str, int defValue)
  2. toInt(String str, int val)
  3. toInt(String string)
  4. ToInt(String string)
  5. toInt(String string)
  6. toInt(String string)
  7. toInt(String string, int defaultValue)
  8. toInt(String string, int defaultValue)
  9. toInt(String text, int defaultValue)