我正在寫一個程序,我應該有用戶輸入一個從0 - 4000年的日期。我應該看看日期是否有效,如果它是一個飛躍一年或沒有。我在代碼中遇到問題。 我得到了一個沒有錯誤的第57行。 我也不確定如何說如果日期有效或不是如何說。 IE:這個日期是有效的,是一個閏年 - 或無效不是一個閏年...等等...驗證日期從用戶輸入
我還是一個初學者,所以我不想爲我寫的代碼,但我想知道如何解決它!謝謝。
import java.util.*;
public class LegalDate //file name
{
public static void main (String [] args)
{
Scanner kb = new Scanner (System.in); //new scanner
//name the variables
int month, day, year;
int daysinMonth;
boolean month1, year1, day1;
boolean validDate;
boolean leapYear;
//ask the user for input
//I asked the MM/DD/YYYY in seperate lines to help me visually with the program
System.out.println("Please enter the month, day, and year in interger form: ");
kb.nextInt();
//now I'm checking to see if the month and years are valid
if (month <1 || month >12)
{ month1 = true;}
if (year <0 || year >4000)
{year1= true;}
//I'm using a switch here instead of an if-else statement, which can also be used
switch (month) {
case 1:
case 3:
case 5: //months with 31 days
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6: //months with 30 days
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) //formula for leapyear
numDays = 29;
{
system.out.println("is a leap year");
}
else
numDays = 28;
{
system.out.println("is not a leap year");
}
break;
default:
System.out.println("Invalid month.");
break;
if (month1 == true)
if (day1 == true)
if (year1 == true)
System.out.println ("date is valid ");
else
if (month1 == false)
System.out.println ("date is invalid");
else
if (day1 == false)
System.out.println ("date is invalid");
else
if (year1 == false)
System.out.println ("date is invalid");
}}
}
謝謝!我知道我的代碼是草率的,但我不知道它是多麼的分散。感謝您的幫助! – cargoboom
我acuually有一個問題,我們還沒有得到這部分尚未在我的課程'System.out.printf(「%n日期是%s有效,是%閏年%n」,validDate?「」:「不是「,leapYear?」「:」不「)kb.close(); 「我一直在試圖找出它是什麼,但你怎麼用這個?你用它來取代if-else語句嗎? – cargoboom
printf是一種用變量替換佔位符(%s代表字符串,%d代表數字等)的方法,%n是換行符。 'condition'? 'execute_if_true':'execute_if_false'就像你所說的那樣,是if/else的簡寫形式。 因此,如果日期無效,則在第一個%s中插入「not」,如果日期不是閏年,則類似地爲第二個%s(否則插入空字符串)。 kb.close()只是釋放與您的掃描儀相關的資源。這將在您結束程序時自動發生,但最好手動進行。 – Dimpl