日期:2014-05-20 浏览次数:20946 次
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); } }
------解决方案--------------------
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); } } } }