用java中的for循环,做以下例题:输入某年某月某日,判断这一天是这一年的第几天?
这个网上找一下一大堆,通过baidu找了一个,可以跑的通的,具体如下:
以下是Java代码实现:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入年份: ");
int year = sc.nextInt();
System.out.print("请输入月份: ");
int month = sc.nextInt();
System.out.print("请输入日期: ");
int day = sc.nextInt();
int sum = 0;
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 判断是否为闰年
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
daysInMonth[1] = 29;
}
// 计算天数总和
for (int i = 0; i < month - 1; i++) {
sum += daysInMonth[i];
}
sum += day;
// 输出结果
System.out.println(year + "年" + month + "月" + day + "日是该年的第" + sum + "天。");
}
}
运行结果示例:
请输入年份: 2023
请输入月份: 4
请输入日期: 21
2023年4月21日是该年的第111天。
代码解释:
Scanner
类获取用户输入的年、月、日。daysInMonth
的整型数组,数组中存储每个月的天数。for
循环计算输入日期在该年中是第几天,累加每个月的天数。如果以上回答对您有所帮助,点击一下采纳该答案~谢谢
来自GPT
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
System.out.print("请输入月份:");
int month = scanner.nextInt();
System.out.print("请输入日期:");
int day = scanner.nextInt();
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days = 0;
for (int i = 0; i < month - 1; i++) {
days += daysInMonth[i];
}
days += day;
if (month > 2 && (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)) {
days += 1;
}
System.out.println(year + "-" + month + "-" + day + "是这一年的第" + days + "天");
}
}
运行结果:
请输入年份:2022
请输入月份:9
请输入日期:19
2022-9-19是这一年的第262天
以上代码可以通过输入年份、月份和日期来计算这一天是这一年的第几天。其中,daysInMonth 数组包含了每个月的天数,首先用一个 for 循环将月份之前的天数累加起来,再加上日期即可得到结果。需要注意的是,如果是闰年的话,2 月会有一个额外的天数。