gpt4 book ai didi

java - 我不知道如何将此 if 语句放入 while 循环中

转载 作者:行者123 更新时间:2023-11-30 08:13:25 24 4
gpt4 key购买 nike

我刚刚开始编码,我正在尝试编写一个代码,让用户必须猜测特殊的日子。它正在工作,但我试图通过添加 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!");
}
}
}

请不要讨厌,我是这方面的新手。

最佳答案

就像 Benjy Kessler 所说,if 语句需要位于 while 循环中。我还修复了你的 if 逻辑。

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) || (Month == 2 && Day > 18))
System.out.println ("That's after the Special Day, try again!");
else if ((Month < 2) || (Month == 2 && Day < 18))
System.out.println ("That's before the Special Day, try again!");
}

关于java - 我不知道如何将此 if 语句放入 while 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com