我的任務是製作一個程序,允許用戶輸入他們的出生日期,並輸出他們的中國生肖動物和他們的占星術標誌。該程序認爲,月份是未聲明的變量,但我試圖讓它們的值爲變量「月」。如何使用字符串作爲輸入值?
下面是代碼,
int day, year;
String month;
System.out.println("Enter the month you were born.");
month=in.nextLine();
System.out.println("Enter day you were born.");
day=in.nextInt();
System.out.println("Enter the year you were born.");
year=in.nextInt();
if (month==January && day <=20)
System.out.println("You are a Capricorn.");
if (month==January && day > 20)
System.out.println ("You are an Aquarius.");
if (month==February && day <= 19)
System.out.println ("You are an Aquarius.");
if (month==February && day >19)
System.out.println ("You are a Pisces.");
if (month==March && day <= 20)
System.out.println ("You are a Pisces.");
if (month==March && day > 20)
System.out.println ("You are an Aries.");
if (month==April && day <= 20)
System.out.println ("You are an Aries.");
if (month==April && day >20)
System.out.println ("You are a Taurus.");
if (month==May && day <= 21)
System.out.println ("You are a Taurus.");
if (month==May && day > 21)
System.out.println ("You are a Gemini.");
if (month==June && day <= 21)
System.out.println ("You are a Gemini.");
if (month==June && day >21)
System.out.println ("You are a Cancer.");
if (month==July && day <=22)
System.out.println ("You are a Cancer.");
if (month==July && day >22)
System.out.println ("You are a Leo.");
if (month==August && day <=22)
System.out.println ("You are a Leo.");
if (month==August && day >22)
System.out.println ("You are a Virgo.");
if (month==September && day <=23)
System.out.println ("You are a Virgo.");
if (month==September && day >23)
System.out.println ("You are a Libra.");
if (month==October && day <=23)
System.out.println ("You are a Libra.");
if (month==October && day >23)
System.out.println ("You are a Scorpio.");
if (month==November && day <=22)
System.out.println ("You are a Scorpio.");
if (month==November && day >22)
System.out.println ("You are a Sagittarius.");
if (month==December && day <=21)
System.out.println ("You are a Sagittarius.");
else
System.out.println ("You are a Capricorn.");
'month ==「January」'不是個好主意,'month.equals(「January」)'會在Java中工作得更好 –
Thanks guys guys。還早,還沒有喝咖啡;) – BlackHatSamurai
@AlexShesterov事實上,一個更好的主意是''1月'.equals(month)'以避免NPE。 –