gpt4 book ai didi

java - 如何使用字符串作为输入值?

转载 作者:行者123 更新时间:2023-12-01 07:53:40 26 4
gpt4 key购买 nike

我的任务是制作一个程序,允许用户输入他们的出生日期,然后它将输出他们的十二生肖和星座。该程序认为月份是未声明的变量,但我试图使它们的值与变量“月份”相同。

这是代码,

<小时/>
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.");

最佳答案

您需要通过在月份字符串中添加双引号来创建月份字符串:

if (month.equals("January") && day <=20)
System.out.println("You are a Capricorn.");

意识到用户必须准确输入“January”,因此“january”不起作用。要实现此目的,请确保使用 toLower 函数。您还可以使用equalsIgnoreCase()

每个月都遵循相同的模式。任何时候使用字符串文字时,它都需要位于 "" 中。另外,如果您要比较字符串,则需要使用 equals(),如上所示。

正如 Luiggi 在下面的评论中指出的那样,这样做更有意义:

 if ("January".equals(month) && day <=20)

这将避免可能出现的NullPointerException错误。

关于java - 如何使用字符串作为输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33241823/

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