本文主要是介绍三天打渔两天晒网(Java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
三天打渔两天晒网
某人三天打渔两天晒网,假设他从1990年1月1日开始打渔三天,然后晒网两天,请编程回答任意的一天他在打渔还是晒网。
A boy works for 3 days while has a 2 days off. If he is working on 1st, Jan, 1990, then for a date entered from the keyboard,
please write a program to determine what the boy is doing, working or resting?
Examples of input and output:
1)Input:
1990-01-05
Output:
He is having a rest.
2)Input:
1990-01-07
Output:
He is working.
3)Input:
1990-01-33
Output:
Invalid input.
输入数据格式:“%4d-%2d-%2d”
输出数据格式:“Invalid input.“或"He is having a rest.” 或"He is working.”
import java.util.Scanner;/*** @author HIT_Tsukinai*/
class Year {int year;int yearDay = 0;public Year(int year) {this.year = year;}public int getYear() {if (this.year - 1990 == 0) {return 0;} else {for (int i = 1; i <= this.year - 1990; i++) {if (i % 4 == 1 && ((1990 + i) % 100) != 0) {yearDay += 366;} else if (this.year % 400 == 0) {yearDay += 366;} else {yearDay += 365;}}return yearDay;}}public int isLeap() {if (year % 4 == 0 && year % 100 != 0) {return 1;} else if (year % 400 == 0) {return 1;} else {return 0;}}
}class Month {int month;int monthDay = 0;int[][] everyDay = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};int flag;int day;public Month(int flag, int month, int day) {this.flag = flag;this.month = month;this.day = day;}public int getMonth() {if (flag == 0) {for (int i = 0; i < month - 1; i++) {monthDay += everyDay[flag][i];}} else {for (int i = 0; i < month - 1; i++) {monthDay += everyDay[flag][i];}}return monthDay + this.day;}
}public class Test {public static void main(String[] args) {Scanner scan = new Scanner(System.in);String[] date;date = scan.next().split("-");//输入用‘-’分割,故调用了字符串的split方法int year = Integer.parseInt(date[0]);//Integer.parseInt方法可以将整型数字字符串转换为整型数字,同理还有double.parseDouble可以转换浮点字符串int month = Integer.parseInt(date[1]);int day = Integer.parseInt(date[2]);Year y = new Year(year);Month m = new Month(y.isLeap(), month, day);if (year < 1990 || month < 1 || month > 12 || day < 1 || day > m.everyDay[y.isLeap()][month]) {System.out.println("Invalid input.");System.exit(0);}int allDay = y.getYear() + m.getMonth();int flag = allDay % 5;switch (flag) {case 1, 2, 3 -> {System.out.println("He is working.");}case 4, 0 -> {System.out.println("He is having a rest.");}}}
}
tips:
split 方法参数为stringObj.split([separator,[limit]])
stringObj(必选项) ,指要被分解的 String 对象或文字。该对象不会被 split 方法修改。
separator(可选项),指字符串或正则表达式对象,它标识了分隔字符串时使用的是一个还是多个字符。如果忽略该选项,返回包含整个字符串的单一元素数组。
limit(可选项)该值用来限制返回数组中的元素个数。
接下来我将学习正则表达式来处理字符串
这篇关于三天打渔两天晒网(Java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!