gpt4 book ai didi

java - 如何以日历格式打印数组中的值?

转载 作者:太空宇宙 更新时间:2023-11-04 13:21:53 24 4
gpt4 key购买 nike

所以我有两个月的数组来存储事件时间、日期和优先级,称为:

Events[] september= new Events[30];
Events[] october = new Events[31];

我想在其中插入我的日期数组并使它们以特定格式显示。

 static String[] days = {"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"};

如何获得这样的输出?我似乎找不到解决办法:

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

我为它编写了两个不同的代码我的代码是:

public static void DisplayEvents(Events[] event,int firstWeekday) {
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
for(int i =0; i<days.length;i++) {
System.out.println(String.format("%1$5s", days[i]) +"");

}

public static void DisplayEvents(Events[] event,int firstWeekday) {
int weekDayIndex =0;

System.out.println("Sun Mon Tue Wed Thu Fri Sat");
for(int day=1; day<days.length; day++){
System.out.println(" ");
weekDayIndex++;
}
for(int day =1; day<event.length;day++){
System.out.print(String.format("%1$5s", day));
weekDayIndex++;
if (weekDayIndex== 7){
weekDayIndex = 0;
System.out.println();
} else {
System.out.println("");
}
}

}

这些代码给我的输出是:

更新的输出:

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

星号表示举办 Activity 的日期。我已经编写了一段代码来放入随机事件,并且我有我的星号。我的问题只是以日历格式打印它,并能够将我的星号放在有事件的日子上。任何贡献/帮助将不胜感激。如果需要,我可以提供更多信息。

最佳答案

您可以打印标题。下一步打印出空格。

int currentWeekDay = 0;
for(int i = 0; i<firstWeekDay; i++){
System.out.print(" ");
currentWeekDay++;
//just in case the firstWeekDay is invalid.
if(currentWeekDay==7){
currentWeekDay=0;
System.out.println();
}
}

现在打印出数字并每次添加硬回车。

for(int i = 0; i<event.length; i++){
System.out.printf("%4s", event[i]);
currentWeekDay++;
if(currentWeekDay==7){
currentWeekDay=0;
System.out.println();
}
}

请注意,我使用的是您创建的 days 字符串数组,而不是格式化您正在迭代的索引。

关于java - 如何以日历格式打印数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32984743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com