嗨,这是我用于我的应用程序的代码。然而,在某些情况下输入数据时会使用if-else语句和嵌套的if-else语句显示不同System.out.print的一个长答案。我需要做些什么才能显示一个答案?我希望程序显示输入的日期,以显示其是否为有效日期,输入的日期是否为闰年,以及如果日期或月份输入错误则显示错误
package javaapplication18;
import java.util.Scanner;
/**
*
* @author Thurston Pietersen
*/
public class JavaApplication18
{
public static void main(String[] args)
{
int sI,fI ,sL, month, day, year;
String mm, dd, yyyy, date;
Scanner keyboard = new Scanner(System.in);
// TODO code application logic here
System.out.print("Input date using the following format mm/dd/yyyy: ");
date = keyboard.next();
sL = date.length();
fI = date.indexOf("/");
sI = date.lastIndexOf("/");
mm = date.substring(0,fI);
month = Integer.parseInt(mm);
dd = date.substring((fI+1),sI);
day = Integer.parseInt(dd);
yyyy = date.substring((sI+1),sL);
year = Integer.parseInt(yyyy);
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31)
System.out.print(date + " is an invalid date.");
else
System.out.print(date + " is a valid date.");
case 4:
case 6:
case 9:
case 11:
if (day > 30)
System.out.print(date + " is an invalid date.");
else
System.out.print(date + " is a valid date.");
case 2:
if (year % 4 == 0)
if (day > 29)
System.out.print(date + " is an invalid day.");
else
System.out.print(date + " is a valid date and leap year.");
else
if (day > 28)
System.out.print(date + " is an invalid day.");
else
System.out.print(date + " is a valid date.");
default:
System.out.println("The date: " + date + " has an invalid month");
}
}
}
答案 0 :(得分:2)
您在所有情况下都遗漏了break
。由于这个原因,开关掉了,所有的情况都被执行了。在适当的位置插入break
:
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31)
System.out.print(date + " is an invalid date.");
else
System.out.print(date + " is a valid date.");
break; // Here
case 4:
case 6:
case 9:
case 11:
if (day > 30)
System.out.print(date + " is an invalid date.");
else
System.out.print(date + " is a valid date.");
break; // Here
case 2:
if (year % 4 == 0)
if (day > 29)
System.out.print(date + " is an invalid day.");
else
System.out.print(date + " is a valid date and leap year.");
else
if (day > 28)
System.out.print(date + " is an invalid day.");
else
System.out.print(date + " is a valid date.");
break; // Here
default:
System.out.println("The date: " + date + " has an invalid month");
}
请尽量将if
和else
用花括号括起来。