例如:输入是' 03/10 / 2016'在' MM / dd / yyyy'。总天数为69.确保计算闰年,以确定2月有28天还是29天。在Java中
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Month;
int Year;
int Day;
int cal = 0, num, Tot = 365;
System.out.print("Please enter the Month");
Month = input.nextInt();
System.out.print("Please enter the Year");
Year = input.nextInt();
System.out.print("Please enter the Day");
Day = input.nextInt();
if (Month == 2) {
if (Year % 4 == 0)
num = 29;
else
num = 28;
} else if (Month == 1 || Month == 3 || Month == 5 || Month == 7
|| Month == 8 || Month == 10 || Month == 12)
num = 31;
else
num = 30;
if (Tot != 365) {
System.out.println("Not valid");
} else {
cal = Tot - Day;
System.out.println("Remaining month of Days=" + cal);
}
}
答案 0 :(得分:0)
试试这个:
public static void main(String[] strings) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a month number: ");
int month = input.nextInt();
System.out.print("Enter a year: ");
int year = input.nextInt();
input.close();
LocalDate date = LocalDate.of(year, Month.of(month), 01);
int length = date.getMonth().length(false);
System.out.print(Month.of(month).getDisplayName(TextStyle.FULL,
Locale.US)
+ " " + year + " has " + length + " days");
}
答案 1 :(得分:0)
您的代码有几个缺陷:
我已更改您的代码以反映这些要点(我会让您参加练习以检查输入的日期和月份是否有效):
import java.util.Scanner;
public class DayOfYear {
private static int[] MONTH_LENGTHS = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int month;
int year;
int day;
int remainingDays = 0, numDays = 0, totalDays = 365;
System.out.println("Please enter the Month: ");
month = input.nextInt();
System.out.println("Please enter the Year: ");
year = input.nextInt();
System.out.println("Please enter the Day: ");
day = input.nextInt();
if (isLeapYear(year)) {
totalDays++;
}
for (int iMonth = 1; iMonth < month; iMonth++) {
numDays += MONTH_LENGTHS[iMonth];
if (iMonth == 2 && isLeapYear(year)) {
numDays++;
}
}
numDays += day;
remainingDays = totalDays - numDays;
System.out.println("Number of days since start of the year = " + numDays);
System.out.println("Remaining days of the year = " + remainingDays);
}
private static boolean isLeapYear(int year) {
return year % 4 == 0 && year != 2000;
}
}