67,541
社区成员
发帖
与我相关
我的任务
分享
//一JAVA正则表达式 要求输入只能是数字,包括小数,前后位数可以调节
//如 小数点前3位后2位 则匹配范围是 0.00~~999.00 其中整数也在内。 如999,0都应该匹配
//楼主没有说清楚,不知道小数点前2位后3位的话,0.0是否算匹配,这里我假设0.1不能匹配,0.10能匹配,00.0不能匹配,00.10匹配
import java.io.*;
import java.util.regex.*;
public class MatcherNumber{
public static void main(String[] args){
BufferedReader bf = null;
int bp = 0;
int ap = 0;
String snum = null;
boolean end = false;
try{
bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please input the digits before the point:");
String bpstr = bf.readLine();
//其实也可以不用转成int型,直接用也可以,但输入一定要是数值。
//如果做的好一点可以再写个正则表达式做下bpstr和bp的数字匹配。
bp = Integer.valueOf(bpstr);
if(bp<=1){
System.out.println("wrong digits!");
return;
}
System.out.println("Please input the digits after the point:");
String apstr = bf.readLine();
ap = Integer.valueOf(apstr);
if(ap<=1){
System.out.println("wrong digits!");
return;
}
while(!end){
System.out.println("Please input a number:");
snum = bf.readLine();
if(snum.equals("")||snum.equalsIgnoreCase("exit"))end = true;
else checkNum(bp,ap,snum);
}
bf.close();
}catch(IOException ie){
ie.printStackTrace();
}
}
//其实checkNum完全可以写在try中,这里我只是为了看得清楚点。
public static void checkNum(int bp,int ap,String snum){
Matcher m = Pattern.compile("[0-9]{1,"+bp+"}\\.[0-9]{"+ap+"}").matcher(snum);
if(m.matches())System.out.println("ture!the number is in range!");
else System.out.println("false!the number is out of range");
}
}