读取字符串,转为为不同类型

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class InputData {
private BufferedReader buf=null;
public InputData(){
this.buf = new BufferedReader(new InputStreamReader(System.in));
}
public String getString(String info){
String temp = null;
System.out.println(info);
try{
temp = this.buf.readLine();
}catch(Exception e){
e.printStackTrace();
}
return temp;
}
public int getInt(String info,String err){
int temp = 0;
String str=null;
boolean flag = true;
while(flag){
str = this.getString(info);
if(str.matches("^\\d+$")){
temp = Integer.parseInt(str);
flag = false;
}else{
System.out.println(err);
}
}
return temp;
}
public float getFloat(String info,String err){
float temp = 0;
String str=null;
boolean flag = true;
while(flag){
str = this.getString(info);
if(str.matches("^\\d+.?\\d*$")){
temp = Float.parseFloat(str);
flag = false;
}else{
System.out.println(err);
}
}
return temp;
}
public Date getDate(String info,String err){
Date temp = null ;
String str=null;
boolean flag = true;
while(flag){
str = this.getString(info);
if(str.matches("^\\d{4}-\\d{2}-\\d{2}$")){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
temp = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
flag = false;
}else{
System.out.println(err);
}
}
return temp;
}


}




应用示例




import java.util.Date;


public class InputDataDemo {


/**
* @param args
*/
public static void main(String[] args) {


InputData input = new InputData();
float f = input.getFloat("请输入小数:", "输入小数的格式不对,请重新输入:");
System.out.println("输入的小数为:"+f);
Date d= input.getDate("请输入日期:","输入日期的格式不对,请重新输入:");
System.out.println("输入的日期为:"+d);



}


}



转载于:https://my.oschina.net/liangxiao/blog/120412

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值