编辑:我不允许使用扫描仪。我知道,它更好。
此程序的目的是接受来自用户的闰四位整数并确定它是否是闰年,通知用户结果,然后提示重置程序以接受另一个条目。如果用户在公元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和1432运行程序的3次迭代的结果。
///// 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
有一些问题。 它始终认为用户输入了#&lt; 1582在第二轮计划中。
在netbeans运行中,在条目是否是闰年的结果之后有空格,用户必须按一个键继续复位提示,由于某种原因,命令提示符旁路。它不一定是个问题,事实上它更好,但它可能与问题有关。
无论在重置提示中输入什么,程序在第二次迭代后结束。
答案 0 :(得分:0)
可以在a System.out.println(readCh);
readCh = (int)System.in.read();
吗?
我不明白为什么你有这条线:
year=(int)System.in.read(); //Clears year from the buffer.
您可以用年份= 0来清除年份;