小游戏算年龄
有这样一个小游戏,你可以按照下面的步骤一步一步地完成:
(1)你一般一个星期中哪一天最忙呢?如果是星期一,则选1,如果是星期二,则选2,依此类推,从1、2、3、4、5、6、7中选一个数字;
(2)将这个数字乘2;
(3)如果你是男生,则将得到的结果加4,如果你是女生,则将得到的结果加8;
(4)将得到的结果乘以50;
(5)如果你是在1 ~ 6月出生,则将得到的结果加2002,如果你是在7 ~ 12月出生,则将得到的结果加3002;
(6)将得到的结果减去你出生的年份(例如1988);
(7)取结果的后两位,得到一个两位数,将这个两位数加10。
你一定会感到惊奇,最后得到的结果竟然是你现在的年龄。请编程实现上述游戏的计算过程,并输出年龄的计算结果。(要求对不符合要求的输入提示"Invalid input." 并不再继续执行以下程序)
输入输出格式:
输出格式控制字符串:
“Please input your busiest day.\n”
“Please input your gender.\n”
“Please input your birthday.\n”
“Your age is:%d\n”
“Invalid input.\n”
输入格式控制字符串:
“%d”
" %c"
“%4d-%2d-%2d”
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please input your busiest day.");
int week = scan.nextInt();
if (week < 1 || week > 7) {
System.out.println("Invalid input.");
System.exit(0);
}
week /= 2;
System.out.println("Please input you gender.");
char gender = scan.next().charAt(0);
if (gender == 'm') {
week += 4;
} else if (gender == 'f') {
week += 8;
} else {
System.out.println("Invalid input.");
System.exit(0);
}
week *= 50;
System.out.println("Please input your birthday.");
String birthday;
birthday = scan.next();
int month = (birthday.charAt(5) - '0') * 10 + (birthday.charAt(6) - '0');
int year = (birthday.charAt(0) - '0') * 1000 + (birthday.charAt(1) - '0') * 100 + (birthday.charAt(2) - '0') * 10 + (birthday.charAt(3) - '0');
int day = (birthday.charAt(8) - '0') * 10 + (birthday.charAt(9) - '0');
if (birthday.length() != 10 || birthday.charAt(4) != '-' || birthday.charAt(7) != '-') {
System.out.println("Invalid input.");
System.exit(0);
} else if (month < 1 || month > 12) {
System.out.println("Invalid input.");
System.exit(0);
}
int[][] dday = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
int flag = 1;
if (year % 4 != 0) {
flag = 0;
} else if (year % 400 != 0) {
flag = 0;
}
if (day < 1 || day > dday[flag][month]) {
System.out.println("Invalid input.");
System.exit(0);
}
if (month <= 6) {
week += 2002;
} else {
week += 3002;
}
week -= year;
week %= 100;
System.out.printf("Your age is:%d", week + 10);
}
}
tips:Java没有格式化输入,也许有但目前我还未掌握,所以在格式化输入生日时我只能用土方法,将字符串中的字符一个个拿来处理,所以非常繁琐,如果大佬有简单方法请务必赐教,但是Java有类似c语言的格式化输出System.out.printf,这点还是非常方便的