前几天,老师刚刚讲完怎样用Java语言输出正确的生日,并且留了一个课后作业。
很喜欢我们老师的讲课方式,她是先让同学自己写,然后再讲。这样可以让我们有思
考的过程。
下面就是我的课后作业,有同学帮助哟!
import java.util.Scanner;
public class KH {
//类的文件名的第一个字母要大写!public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//do……while循环结构
do{
System.out.println("请输入你的出生日期:(1999/12/10)");
String birthday=input.next();int index=birthday.indexOf("/");
//第一个"/"的位置
int lastIndex=birthday.lastIndexOf("/");
//第二个"/"的位置
if(birthday.indexOf("/")==4&&birthday.lastIndexOf("/")>birthday.indexOf("/") && birthday.length()==10){
//第一个"/"的位置是4并且第二个"/"的位置是10且大于第一个"/"的位置
int year=Integer.parseInt(birthday.substring(0,index));
//将string类型转化成int类型
//birthday.substring(0,index)输出你输入"/"位置前的内容
int month=Integer.parseInt(birthday.substring(index+1,lastIndex));
//birthday.substring(index+1,lastIndex)输出你输入第一个"/"与第二个"/"之间的内容
int day=Integer.parseInt(birthday.substring(lastIndex+1));
//birthday.substring(lastIndex+1)输出你输入第二个"/"后的内容
//switch循环结构case1、3、5、7、8、10、12(这几个月份是31天)套用一个,case2、4、6、9、11(这几个月份是30天)套用一个case2(二月份要判断闰年和平年)
switch(month){case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(day>31){
System.out.println("你输入的格式不对,请重新输入!");
}else{
System.out.println("你的出生日期为:"+year+"年"+month+"月"+day+"日");
System.exit(0);
//系统退出
}break;
//跳出循环
case 4:case 6:
case 9:
case 11:
if(day>30){
System.out.println("你输入的格式不对,请重新输入!");
}else
System.out.println("你的出生日期为:"+year+"年"+month+"月"+day+"日");
System.exit(0);}
break;
case 2:
if(day==29){
if(year%4==0){
System.out.println("你的出生日期为:"+year+"年"+month+"月"+day+"日");
System.exit(0);
}else{
System.out.println("你输入的格式不对,请重新输入!");
}
}else if(day<29){
System.out.println("你的出生日期为:"+year+"年"+month+"月"+day+"日");
System.exit(0);
}else{
System.out.println("你输入的格式不对,请重新输入!");
}
break;
default:
System.out.println("你输入的格式不对,请重新输入!");
break;
}
}else{
System.out.println("你输入的格式不对,请重新输入!");
}
}while(true);
//死循环
}
}