您的位置:首页 > 编程语言 > Java开发

从控制台输入一个日期,要求必须以09/30(月/日)的格式输入

2018-04-09 11:11 218 查看
实现思路
(1)控制台获取输入的日子。
(2)分析是否存在“/”以及它的位置是否正确。
(3)分析字符串长度是否超过了5个长度。
(4)分析月份是否大于12,天数是否大于31(不做精确判断,不区分月份应该有30或31天的情况)
(5)选做:精确判断月份应有30或31或者28的情况,如何格式不正确,实现重复输入。
实现步骤
(1)创建Date类,实现控制台录入数据。
(2)使用String对象的indexOf()方法及length()方法分别获取“/”的位置及字符串的长度。
(3)判断字符串中是否存在“/”或者“/”的位置是否正确以及字符串长度是否合法。
(4)格式合法后分别截取月份和日的部分转换格式,判断是否为合法日期。
代码提示,其中Integer.parseInt()是将字符串类型的变量转换为整数类型,以便后面进行日的合法性判断.
public class `Rw2{

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input= new Scanner(System.in);
while(true){
System.out.println("请输入你的生日:(02/27)");
String date=input.next();
if(date.indexOf("/")!=-1 && date.indexOf("/")==2 && date.length()==5){
String month = date.substring(0, 2);
int yue = Integer.parseInt(month);
int ri = Integer.parseInt(date.substring(date.indexOf("/")+1));
if(yue>=1&&yue<=12){
switch(yue){
case 1:
   case 3:
   case 5:
   case 7:
   case 8:
   case 10:
   case 12:
    if(ri>=1 && ri<=31){
    System.out.println("你的生日是"+date);
    System.exit(0);
    }else{
    System.out.println("请输入正确的日期");
    break;
    }
   case 4:
   case 6:
   case 9:
   case 11:
    if(ri>=1 && ri<=30){
    System.out.println("你的生日是"+date);
    System.exit(0);
   
    }else{
    System.out.println("请输入正确的日期");
    break;
    }
   default:
           if(ri>=1 && ri<=28){
           System.out.println("你的生日"+date);
           System.exit(0);
           }else{
           System.out.println("请输入正确的东西");
           break;
           }
}
}else{
System.out.println("输入的“月”不正确");
}
}else{
System.out.println("输入的格式不正确");
}

} }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java
相关文章推荐