java中的String转int需要注意的问题

1。null,”“,(空,空串)
2。满足:首字符为+,-,数字,
不满足:其它的例如字母,空格串
3。溢出(先用long获取,若不满足,则返回错误)
具体代码:

package StringExercise;

/**
 * @author wangpei
 * @version 创建时间:2017年3月24日 上午12:16:50 类说明
 */
public class StringToInt {// 字符串转整数
    static String s = "    ";
    static boolean b = true;

    public static void main(String[] args) {// 对所有可能出现的情况加以考虑
        int result = change(s);
        if (b == false)
            System.out.println("输入不正确");
        else
            System.out.println("转换后:" + result);

    }

    public static int change(String str) {
        System.out.println(str.isEmpty());

        if (s == null || s != null && s.equals("")) {// 输入非法结束。
            b = false;
            return 0;
        }

        if (str.charAt(0) == '-' || str.charAt(0) == '+'
                || (str.charAt(0) >= '0' && str.charAt(0) < '9')) {// 负数
            long l = IsOutOfMax(str);
            return (int) l;
        } else {// 非法输入,直接结束
            b = false;
            return 0;
        }
    }

    public static long IsOutOfMax(String s) {
        long l = 0;
        l = Long.parseLong(s);
        if (l < -2147483648 || l > 2147483647) {
            b = false;
            return 0;
        } else
            return l;
    }

}

定义boolean类型的b作用:判断返回的0是输入错误的0,还是转换来的0;

posted @ 2017-03-24 01:10  多巴胺二次元式  阅读(397)  评论(0编辑  收藏  举报