【发布时间】:2016-04-26 20:36:10
【问题描述】:
我对 Java 还很陌生,我正在尝试制作一个允许我输入一个月,然后输入一天的程序。如果月内的一天有效(即 2 月 28 日有效,29 日无效),我希望它结束。我已经让它工作了,但是我每个月都使用了 12 条 IF 语句,它看起来太乱了,而且像太多的代码。 任何人都可以提出一种更好的浓缩方法吗?
import java.util.Scanner;
public class Calender {
public static void main(String[] args) {
int month=0;
int day=0;
Scanner in = new Scanner (System.in);
do {
System.out.print("Enter a month [1..12]: ");
month=in.nextInt();
//continue;
} while (month > 12);
//System.out.println ("This is not a valid month.");
do {
System.out.print("Enter a day [1..31]: ");
day=in.nextInt();
} while (day > 31);
if (day > 31 && month == 1) {
System.out.print("This is not a valid day of the month");
}
if (day > 31 && month == 3) {
System.out.print("This is not a valid day of the month");
}
if (day > 31 && month == 5) {
System.out.print("This is not a valid day of the month");
}
if (day > 31 && month == 7) {
System.out.print("This is not a valid day of the month");
}
if (day > 31 && month == 8) {
System.out.print("This is not a valid day of the month");
}
if (day > 31 && month == 10) {
System.out.print("This is not a valid day of the month");
}
if (day > 31 && month == 12) {
System.out.print("This is not a valid day of the month");
}
if (day > 30 && month == 4) {
System.out.print("This is not a valid day of the month");
}
if (day > 30 && month == 6) {
System.out.print("This is not a valid day of the month");
}
if (day > 30 && month == 9) {
System.out.print("This is not a valid day of the month");
}
if (day > 30 && month == 11) {
System.out.print("This is not a valid day of the month");
}
if (day > 28 && month == 2) {
System.out.print("This is not a valid day of the month");
}
}
}
【问题讨论】:
-
抱歉,最后的 IF 语句应该是 '2' 而不是 '4'
-
您可以编辑您的帖子以纠正您在原始帖子中所犯的错误。
-
使用一个 int 数组来保存每个月的天数。那么你只需要一个 if 语句,比如:
if (day > months[month] || day <= 0) -
查找
switch-case语句。 -
这个问题最好在SE CodeReview提出
标签: java if-statement