java - 如何根据 Java 中的用户输入格式化日历
问题描述
我有一个任务,询问用户当月的开始日期(0 代表星期日,1 代表星期一等)。
以下是我尝试过的代码:
import java.util.Scanner;
public class CalendarMonth {
public static void main(String[] args) {
new CalendarMonth().runApp();
}
void runApp() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the start day: ");
int startDay = in.nextInt();
System.out.print("Enter the number of days: ");
int daysMonth = in.nextInt();
System.out.println("Sun\tMon\tTue\tWed\tThu\tFri\tSat");
System.out.println("---\t---\t---\t---\t---\t---\t---\t");
//determine starting day with spaces
startDay%=7;
//System.out.println("startDay value is " + startDay);
for(int i = 0; i<=startDay;i++){
System.out.print("X"); //prints a space for each empty day
}
for(int j = 1; j <= daysMonth; j++){
if (j < 10){
System.out.print(" ");
}
if (startDay%7 == 0){
System.out.print( j + "\n");
}
else{
System.out.print(j + "\t");
}
startDay++;
}
}
}
这是预期的输出:
Enter the start day: 3
Enter the number of days: 30
Sun Mon Tue Wed Thu Fri Sat
--- --- --- --- --- --- ---
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
这是实际输出:
Enter the start day: 3
Enter the number of days: 30
Sun Mon Tue Wed Thu Fri Sat
--- --- --- --- --- --- ---
XXXX 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
日历第一行中的 XXXX 只是一个占位符,直到我弄清楚如何格式化它。我已经为此工作了很多小时,我想我需要帮助,如果慷慨的话,我可能需要一个解释。如果没有,我会尽可能多地从代码中学习。
先感谢您。
解决方案
由于一周从 0 开始到 6 结束,因此新的一周应该在第 7 次迭代时开始一个新行,也就是 startDay 为 6 时。
我将代码更改为:
if (startDay%7 == 6){
System.out.print( j + "\n");
}
将 startDay 的余数除以 7,如果等于 6(即一周结束),则使代码换行。
推荐阅读
- powershell - 测试 PC 是否可以通过网络访问,如果可以,则在 powershell 脚本中运行任务
- azure - 如何将自定义操作添加到 Azure Application Insights 的“性能”选项卡?
- express - RPC 失败;将应用程序部署到 Heroku 时出现 Curl 56 OpenSSL 错误
- c - 为什么每次尝试将元素存储到 C 中的数组时都会出现段错误?
- apache-spark - EMR 集群中的 Spark on Yarn 核心数
- node.js - Node JS Web 应用程序无法连接到 API
- react-testing-library - 强制重新查询元素以触发点击处理程序
- c++ - 使用 soplex 的 makefile 示例
- discord.py - 所以我正在尝试制作赠品机器人命令,但似乎我无法获得链接
- firebase - 客户端 React App 从服务器端生成的 Firestore 模拟器中获取