定义名为: TestException1.java的类
2) 写一个把字符串转成整型的方法,出错时返回默认值
public static int stringToInt(String str, int defaultValue){ //… };

解决方案 »

  1.   

    楼主是在狂问老师布置的作业?
    public static int stringToInt(String str, int defaultValue){
      try {
        return Integer.parseInt(str);
      } catch (Exception ex) {
        return defaultValue;
      }
    }
      

  2.   

    int value = defaultValue;
    try
    {
       value = Integer.parse(str);
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }return value;
      

  3.   

    这个很简单啊
    public class TestException1 {
    public static void main(String args[]){
    String str="222";
    TestException1.stringToInt(str, 0);

    }
     public static int stringToInt(String str, int defaultValue){
     int result = 0;
     try{
     result = Integer.parseInt(str);
     }catch(NumberFormatException e){
     //e.printStackTrace();
     System.out.println("参数不能转化为Integer型,以默认值输出");
     result = defaultValue;
     }
    return result;
     
     }
    }
      

  4.   

          public static int stringToInt(String str) {
    String reg = "\\d{1,}"; //这是正则表达示 str 必须是一位或多位数字组成,
                                                    //否则返回-1
    if (str.matches(reg)) {
    return Integer.parseInt(str);
    } else {
    return -1;
    }
    }
    楼上写的也可以,
    两种办法,楼主自己选吧!