写一个函数,检查字符串是否为整数,如果是,返回其整数值

解决方案 »

  1.   

    Integer i = new Integer(inputStr);
    if(i.equals(inputStr)) return i.intValue();
      

  2.   

    public class Converter {
    public static Object convert(String s){
    try{
    return Integer.valueOf(s);
    }catch(Exception e){
    return new Boolean(false);
    }
    }
    public static void main(String[] args) {
    String s ="12334.222";
    Object o =  convert(s);
    if(o instanceof Integer){
    System.out.println(s+" is an int ,it's value:"+((Integer)o).intValue() );
    }else{
    System.out.println(s+"is not an int. ");
    }
    }

    }
      

  3.   

    刚学正则表达式,你看看行不行,     
            String sampleText = "-222";
            String sampleRegex = "^(-)+[0-9]*$";
            java.util.regex.Pattern p = java.util.regex.Pattern.compile(sampleRegex);        java.util.regex.Matcher m = p.matcher(sampleText);
            boolean result = m.find();
     
            if (result) {
                System.out.println(sampleText);
             }
      

  4.   

    Integer.parseInt()这不是现成的函数吗?还要写?
      

  5.   

    public static int inputInteger()//読んで1つの整数に入る
        {
            int i = 0;
            double d = 0;
            String temp;//定義の1つの標識の位
            boolean result = true;//1つの標識を定義する
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while(result)//表して本当だになって、
            {
                try
                {
                    temp = in.readLine();
                    d = Double.parseDouble(temp);                if (d > 2147483647) //入力の数字はあまりに大きい
                    {
                        System.out.println("大き過ぎて、もう一度入ってください。");
                    }
                    else if(d < -2147483648) //入力の数字はあまりに小さい
                    {
                        System.out.println("あまりに小さく、もう一度入ってください。");
                    }
                    else 
                    {
                        try 
                        {
                            i = Integer.parseInt(temp);//tempを整数に変える、保存はiの中にある
                            //while 終わり
                            result = false;
                        }
                        //捕らえてtempを整数の時の普通でなさになる
                        catch (NumberFormatException nfe) 
                {
                            System.out.println("Tntegerでない、もう一度入ってください:");
                        }
                     }
                }
                catch (NumberFormatException ne) //捕らえてtempをdoubleタイプの時の普通でなさになる
                {
                    System.out.println("キャラクタはご遠慮ください、もう一度入ってください。");
                }
                catch (IOException ioe) //IOException を捕らえる
                {
                    System.out.println("すみません、IOExceptionです。");
                    //while 終わり
                    result = false;
                }
            }
            return i;//iを戻
        }以前做日本项目时候写的一个,只能输入整数,输错了还可以重新输入,并且给出错误的原因。
    楼主你看看你能用上不,要是能用上,需要汉化的话,我还可以帮你。