zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    2016年第七届蓝桥杯C/C++ A组国赛 —— 第一题:随意组合
    寻找段落
    攻击火星
    图论入门
    实数加法
    求 10000 以内 n 的阶乘
    大整数因子
    计算2的N次方
    大整数减法
    大整数加法
  • 原文地址:https://www.cnblogs.com/wangxiaopei/p/8551223.html
Copyright © 2011-2022 走看看