1. 程式人生 > >java實現字串轉化為整數

java實現字串轉化為整數

public class StringToIntTest {
 
    /**
     * @author 曹豔豐  北京大學
     */
    public static void main(String[] args) {
        // TODO 自動生成的方法存根
        try {
            System.out.println(parseInt("cao21'''474fefda8364fe7"));
            System.out.println(parseInt("-2147483648"));
            System.out.println(parseInt("-2147483651"));
            System.out.println(parseInt("-2147483648"));
            System.out.println(parseInt("-21474836410"));
        } catch (MyException e) {
            // TODO 自動生成的 catch 塊
            e.printStackTrace();
        }
 
    }
 
    private static int parseInt(String string) throws MyException {
        /* 異常情況1:字串為null */
        if (string == null) {
            throw new MyException("字串為null!");
        }
        int length = string.length(), offset = 0;
        /* 異常情況2:字串長度為0 */
        if (length == 0) {
            throw new MyException("字串長度為0!");
        }
        boolean negative = string.charAt(offset) == '-';
        /* 異常情況3:字串為'-' */
        if (negative && ++offset == length) {
            throw new MyException("字串為:'-'!");
        }
        int result = 0;
        char[] temp = string.toCharArray();
        while (offset < length) {
            char digit = temp[offset++];
            if (digit <= '9' && digit >= '0') {
                int currentDigit = digit - '0';
                /*
                 * 異常情況4:已經等於Integer.MAX_VALUE / 10,判斷要新增的最後一位的情況:
                 * 如果是負數的話,最後一位最大是8 如果是正數的話最後一位最大是7
                 */
                if (result == Integer.MAX_VALUE / 10) {
 
                    if ((negative == false && currentDigit > 7)
                            || (negative && currentDigit > 8)) {
                        throw new MyException("溢位!");
                    }
                    /*
                     * 異常情況5:已經大於Integer.MAX_VALUE / 10
                     * 無論最後一位是什麼都會超過Integer.MAX_VALUE
                     */
                } else if (result > Integer.MAX_VALUE / 10) {
                    throw new MyException("溢位!");
                }
 
                int next = result * 10 + currentDigit;
                result = next;
            }
        }
        if (negative) {
            result = -result;
        }
        return result;
    }
 
}
 
/* 自定義異常 */
class MyException extends Exception {
    /**
     *
     */
    private static final long serialVersionUID = 1749149488419303367L;
    String message;
 
    public MyException(String message) {
        // TODO 自動生成的建構函式存根
        this.message = message;
    }
 
    @Override
    public String getMessage() {
        // TODO 自動生成的方法存根
        return message;
    }
 
}
****************************