日期的有效验证

这周学习了String字符串一些常用的方法,如:length():字符串的长度;equals():字符串相等......并通过做上机任务5加深了对一些常用方法的了解以及如何对其怎样使用,其中有一道题如下:

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

import java.util.Scanner;
public class Date {
public static void main(String[] args) {
do{
Scanner input=new Scanner(System.in);
System.out.println("请输入你的生日:(02/27)");
String birthday=input.next();
int index=birthday.indexOf("/");
if(birthday.indexOf("/")!=-1 && birthday.indexOf("/")==2){
if(birthday.length()==5){
String month=birthday.substring(0,2);
int yue=Integer.parseInt(month);
int ri=Integer.parseInt(birthday.substring(index+1));
if(yue>=1 && yue<=12){//判断月份是否在1-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("你的生日为"+birthday);
System.exit(0);
}else{
System.out.println("输入有误");
}
break;
case 2:
if(ri>=1 && ri<=28){
System.out.println("你的生日为"+birthday);
System.exit(0);
}else{
System.out.println("输入有误");
}
break;
default:
if(ri>=1 && ri<=30){
System.out.println("你的生日为"+birthday);
System.exit(0);
}else{
System.out.println("输入有误");
}
break;
}
}else{
System.out.println("输入错误");
}
}else{
System.out.println("输入不正确,请重新输入");
}
}else{
  System.out.println("输入错误");
}
}while(true);
}

}

这道题运用了之前学习的循环和字符串方法,其中使用了do......while; switch;if...else...;和刚学习的String字符串中的indexOf()方法:返回字符在此字符串中最后一次出现出的索引。如果未出现则返回-1,索引从0开始,length()......

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值