怎么判断String是不是数字,如果不是数字强制转换成int类型好像会出错。

解决方案 »

  1.   

    public boolean checkNum(String args){
    Pattern p=Pattern.compile("^[\d]*");  //正则表达式
    Matcher m=p.matcher(args);
    if(m.matches())
    return true;
    else
    return false;
    }这是前几天一个帖子问过的,多翻翻旧帖。
      

  2.   

    public int checkNumber(String st){
      int dipage=-1;
      if(st.matches("[\\d]*")){
        try{
    dipage=Integer.parseInt(st);
        }catch(Exception ex){
    dipage=-1;
        }
        return st;
      }else{
       return dipage;
      }
    }
    如果是数字就返回相应的数 如果不是返回-1
      

  3.   

    public static boolean isValidateNumber(String str) throws NumberFormatException{
            if (str==null) {
              return false;
            }
            try {
             Pattern p = Pattern.compile("[\\d]+");
             Matcher m = p.matcher(str);
             return m.matches();
            } catch (Exception e){          e.printStackTrace();
              return false;
            }
          }
      

  4.   

    不好意思倒数第5行 return st;这句 应为return dipage;
      

  5.   

    再发一遍
    public int checkNumber(String st){
      int dipage=-1;
      if(st.matches("[\\d]*")){
        try{
    dipage=Integer.parseInt(st);
        }catch(Exception ex){
    dipage=-1;
        }
        return dipage;
      }else{
       return dipage;
      }
    }
    如果是数字就返回相应的数 如果不是返回-1
      

  6.   

    public boolean isInt(String s)
    {
     boolean b = true;
     try{
       int x  =  Integer.valueOf(s).intValue();
    }catch(Exception e)
    {
      b = false;
    }
    return b;
    }
    用别的方法调用一下这个方法,就行了啊,如果返回的是true 就直接转,否则就不转
      

  7.   

    不是數字的字符串 轉換 當然會報 NumberFormatException..判斷一般 會用 正則表達式..同意iwillrockyou(我为java狂~)的說
      

  8.   

    String str="120.55";
    int dipage=-1;
    if(str.matches("[\\d]+")){
    System.out.println("matches str:"+str);
    try{
    dipage=(int)Integer.valueOf(str).intValue();
    }catch(Exception ex){
    dipage=-1;
    }
    System.out.println("matches:"+dipage);
    }else if(str.matches("[\\d]+((\\.)[\\d]+)?")){
    System.out.println("float matches str:"+str);
    try{
    dipage=(int)Float.valueOf(str).intValue();
    }catch(Exception ex){
    dipage=-1;
    }
    System.out.println("float matches:"+dipage);
    }
    else{
    System.out.println("no matches:"+str);
    }