我的任务是根据用户输入的第一天制作日历。如果是年份,例如。 2 =星期二和年,所以我可以弄清楚它是否是闰年。除了以下情况之外,我设法让一切正常:
当我输入2013 2(意思是1月1日应该是星期二)时,它将1月1日放在星期六。您可以通过转到计算机上的日历并进行比较来检查日期是否正确显示。我查看了代码,但无法弄清楚2在开始时输入的结果是从星期六开始的日期。
我哪里错了?
package javaapplication6;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class JavaApplication6 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter the year and the day as a number eg. 2034 2: ");
int year = input.nextInt();
int day = input.nextInt();
day -= 1;
boolean leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
for(int i = 1; i <= 12; i++){
String wDay = "";
String wMonth = "";
int days = 0;
int current = 0;
switch(i){
case 1: days = 31; day+= 31; wMonth = "January"; break;
case 2: if(leap){days = 29;}else{days = 28;}; if(leap){day += 29;}else{day += 28;}; wMonth = "February"; break;
case 3: days = 31; day+= 31; wMonth = "March"; break;
case 4: days = 30; day+= 30; wMonth = "April"; break;
case 5: days = 31; day+= 31; wMonth = "May"; break;
case 6: days = 30; day+= 30; wMonth = "June"; break;
case 7: days = 31; day+= 31; wMonth = "July"; break;
case 8: days = 31; day+= 31; wMonth = "August"; break;
case 9: days = 30; day+= 30; wMonth = "September"; break;
case 10: days = 31; day+= 31; wMonth = "October"; break;
case 11: days = 30; day+= 30; wMonth = "November"; break;
case 12: days = 31; wMonth = "December"; break;
}
System.out.printf(" %15s\n", wMonth);
System.out.println(" ___________________________");
System.out.printf(" %3s %3s %3s %3s %3s %3s %3s\n", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
for(int space = 0; space <= (day % 7) + 1; space++){
System.out.print(" ");
current ++;
}
for(int date = 1; date <= days; date++){
if(current > 7){
System.out.print("\n ");
current = 1;
}
if(date < 10){
System.out.print(date + " ");
}else{
System.out.print(date + " ");
}
current++;
}
System.out.println("\n");
}
}
}
答案 0 :(得分:1)
你确定它有效吗?我在2014年和3年运行它,它从周日开始。 我做了一些改变,现在我觉得它应该有效:
switch(i){
case 1: days = 31; day+= 0; wMonth = "January"; break;
case 2: if(leap){days = 29;}else{days = 28;}; day += 31; wMonth = "February"; break;
case 3: days = 31; if(leap){day += 29;}else{day += 28;}; wMonth = "March"; break;
case 4: days = 30; day+= 31; wMonth = "April"; break;
case 5: days = 31; day+= 30; wMonth = "May"; break;
case 6: days = 30; day+= 31; wMonth = "June"; break;
case 7: days = 31; day+= 30; wMonth = "July"; break;
case 8: days = 31; day+= 31; wMonth = "August"; break;
case 9: days = 30; day+= 31; wMonth = "September"; break;
case 10: days = 31; day+= 30; wMonth = "October"; break;
case 11: days = 30; day+= 31; wMonth = "November"; break;
case 12: days = 31; day+= 30; wMonth = "December"; break;
}
和
for(int space = 0; space <= (day % 7); space++){ //here u added one space too much.
在你的switch语句中,你加快了几天。在第一个月你已经有一天= 31但你应该有输入的天数 - 1。