![](/img/trans.png)
[英]i can't figure out how to use a while loop with an if statement string comparison
[英]I can't figure out how to put this if statement in my while loop
我只是盯着編碼,我試圖制作一個使用戶不得不猜測特殊日子的代碼。 它正在工作,但是我嘗試通過添加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!");
}
}
}
請不要討厭,我是這個新手。
while應該像:
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);
}
就像本傑·凱斯勒(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!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.