日期:2014-05-20  浏览次数:20902 次

面试题,谢谢
写一个函数,检查字符串是否为整数,如果是,返回其整数值(Java), 


------解决方案--------------------
修改2#代码
Java code
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestInteger {
    static int check(String s) {
        Pattern p = Pattern.compile("[+-]?\\d+");
        Matcher m = p.matcher(s);
        while (m.matches()) {
            return Integer.parseInt(s);
        }
        return -1;
    }

    public static void main(String[] args) {
        String s = "12315465";
        int j = check(s);
        System.out.println("j=" + j);
        String s1 = "-22";
        int k = check(s1);
        System.out.println("k=" + k);
    }
}

------解决方案--------------------
探讨
Java code
import java.util.regex.*;
public class TestInteger {
static int check(String s){
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher(s);
while(m.matches()){
return Integer.parseInt(s);
}
return -1;
}

public static void main(String[] args) {
String s="12315465";
int j=check(s);
Sys…

------解决方案--------------------
Java code

import java.io.*;

public class IsInteger
{
    public static void main(String[] args) throws Exception 
    {
        while(true)
        {
            System.out.print("请输入整数字符串:");
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String s=br.readLine();
            StringBuffer sb=new StringBuffer();
                        for(int i=0;i<s.length();i++)
            {
                if((int)s.charAt(i)>57 ||(int)s.charAt(i)<48)
                {
                    System.out.println("该字符串不是整数,请重新输入");
                    break;
                }
                else
                {
                    sb.append(s.charAt(i));
                }
            }
                        if(s.length()==sb.length())
                        {
                              System.out.println(s);
                        }
        }

    }

}