java 增强版的数据输入

 1 package hjw;
2 import java.io.BufferedReader;
3 import java.io.IOException;
4 import java.io.InputStreamReader;
5 import java.text.ParseException;
6 import java.text.SimpleDateFormat;
7 import java.util.Date;
8 class InputData{
9 private BufferedReader buf=null;
10 public InputData(){
11 this.buf=new BufferedReader(new InputStreamReader(System.in));
12 }
13 public String getString(String info){
14 String t=null;
15 System.out.print(info);
16 try{
17 t=this.buf.readLine();
18 }catch (IOException e){
19 e.printStackTrace();
20 }
21 return t;
22 }
23 public int getInt(String info,String err){
24 int t=0;
25 String str=null;
26 boolean flag=true;
27 while(flag){
28 str=this.getString(info);
29 if(str.matches("^\\d+$")){
30 t=Integer.parseInt(str);
31 flag=false;
32 }else{
33 System.out.println(err);
34 }
35 }
36 return t;
37 }
38 public float getFloat(String info,String err){
39 float t=0;
40 String str=null;
41 boolean flag=true;
42 while(flag){
43 str=this.getString(info);
44 if(str.matches("^\\d+.?\\d+$")){
45 t=Float.parseFloat(str);
46 flag=false;
47 }else{
48 System.out.println(err);
49 }
50 }
51 return t;
52 }
53 public Date getDate(String info,String err){
54 Date d=null;
55 String str=null;
56 boolean flag=true;
57 while(flag){
58 str=this.getString(info);
59 if(str.matches("^\\d{4}-\\d{2}-\\d{2}$")){
60 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
61 try{
62 d=sdf.parse(str);
63 }catch (ParseException e){
64 e.printStackTrace();
65 }
66 flag=false;
67 }else{
68 System.out.println(err);
69 }
70 }
71 return d;
72 }
73 }
74 public class InputDemo {
75 public static void main(String[] args) throws Exception {
76 int i=0;
77 float j=0;
78 InputData ipt=new InputData();
79 i=ipt.getInt("请输入", "必须是数字");
80 j=ipt.getFloat("请输入", "chongshu");
81 System.out.println(i+"\n"+j);
82 }
83 }
原文地址:https://www.cnblogs.com/dennisac/p/2412482.html