編輯:我不能使用的掃描儀。我知道,它更好。正常運行時在NetBeans而不是在命令提示
該程序的目的是接受來自用戶的閏秒四位整數,並確定它是否是閏年,通知用戶結果,然後提示重置程序以接受另一個條目。如果用戶在公元1582年之前輸入日期,它將被拒絕。
public class RevisedLeapYear {
public static void main(String args[])
throws java.io.IOException {
char restartChoice = 'y';
int readCh, year=0, i;
boolean isLeapYear;
while(restartChoice == 'y' || restartChoice == 'Y'){
System.out.print("Enter target year: ");
for(i = 0; i < 4; i++)//start for
{
readCh = (int)System.in.read();
switch(i) //start switch
{//converts in to 4 digits
case 0: year = (int)((readCh - 48) * 1000); break;
case 1: year = year + (int) ((readCh - 48) * 100); break;
case 2: year = year + (int) ((readCh - 48) * 10); break;
case 3: year = year + (int) (readCh - 48);
}//end switch
}//end for
isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));
if(isLeapYear == true && year > 1581){
System.out.println(year + " is a Leap Year! What a time to be alive!");
}
else if(isLeapYear == false && year > 1581){
System.out.println(year + " is not a Leap Year... how unfortunate.");
}
else{
System.out.println("There are no leap years before 1582!");
}
readCh = System.in.read(); // Clear the carriage return in the buffer
readCh = System.in.read(); // Clear the linefeed in the buffer
System.out.print("Reset program? y/n \n");
restartChoice=(char)System.in.read(); //Clears restart choice from the buffer.
year=(int)System.in.read(); //Clears year from the buffer.
}
}//End main
}//End class
我到運行的問題是,在命令提示符下,無論第二項是什麼,它總是會說其不到1582我有同樣的問題,當我在NetBeans開發它,通過使用「year =(int)System.in.read();」清除緩衝區來修復它。該程序在此之後順利運行,但現在使用命令提示符運行時,問題重複出現。
這是試圖運行使用值2916,1900年計劃的3次迭代的結果,1432
///// In Netbeans
Enter target year: 2916
2916 is a Leap Year! What a time to be alive!
Reset program? y/n
y
Enter target year: 1900
1900 is not a Leap Year... how unfortunate.
Reset program? y/n
y
Enter target year: 1432
There are no leap years before 1582!
Reset program? y/n
n
BUILD SUCCESSFUL (total time: 49 seconds)
///// end of program
///// In command prompt
Enter target year: 2916
2916 is a Leap Year! What a time to be alive1
Reset program? y/n
y
Enter target year: 1900
There are no leap years before 1582!
Reset program? y/n
y
///// End of program
有幾件事情是錯誤的。 1.始終認爲用戶輸入的#< 1582上的程序的第二輪。
在NetBeans運行的條目是否是閏年,其中用戶必須按一個鍵以繼續到復位提示,對於一些結果之後有位原因命令提示符繞過此。這不一定是問題,事實上它更好,但它可能與問題有關。
程序不管是在復位提示進入第二次迭代之後結束。
你應該考慮使用'Scanner'用戶輸入。 – FredK
我需要不使用掃描儀。 –