我只是在盯着编码而我正在尝试制作一个能让用户猜出特殊日子的代码。它工作但我试图通过添加while循环来提高效率,以便在用户失败时继续尝试而不必退出并重新启动。代码只是在用户获得第2个月以及18天之上或之后的一天时结束,而不是再次尝试,这里是代码:
import java.util.Scanner;
public class SpecialDay {
public static void main(String[] args) {
int Day, Month;
Scanner scan = new Scanner(System.in);
System.out.print("Welcom to the Special Day guessing game!");
System.out.print(" Enter the Month: ");
Month = scan.nextInt();
System.out.print("Enter the Day: ");
Day = scan.nextInt();
while (Day != 18 && Month != 2) {
System.out.print("Enter the Month: ");
Month = scan.nextInt();
System.out.print("Enter the Day: ");
Day = scan.nextInt();
}
if (Month == 2 && Day == 18) {
System.out.println("Nice! You got the Special Day!");
} else if (Month >= 2 && Day > 18) {
System.out.println("That's after the Special Day, try again!");
} else if (Month <= 2 && Day < 18) {
System.out.println("That's before the Special Day, try again!");
}
}
}
请不要讨厌,我是新手。
答案 0 :(得分:1)
同时应该是:
while ( (Day != 18 || Month != 2) && (Day>=1 && Day<=31 && Month>=1 && Month<=12){
......代码...... }
也可以与do while
一起使用,如:
do{
...the code...
}while ( (Day != 18 || Month != 2) && (Day>=1 && Day<=31 && Month>=1 && Month<=12);
也可以写成一个函数:
private boolean validateDayMonth(int Day, int Month){
return ( (Day != 18 || Month != 2) && (Day>=1 && Day<=31 && Month>=1 && Month<=12);
}
答案 1 :(得分:0)
就像Benjy Kessler所说,if语句需要在while循环中。我也修复了你的if逻辑。
MerlinDevice