所有变量均已正确初始化,并且仅在此方法内定义,将day调用为整数,然后设置为可读取的字符串,然后拆分为字符以创建单词格式。
另外,使用dayL(整数)的数学有时会返回StringIndexOutOfBounds异常,我理解这是由于使用.length()创建的不等式导致的错误所致。
感谢您的任何帮助。
public static void bday()
{
s_day = Integer.toString(day);
dayL = s_day.length();
switch (dayL)
{
case 1:
if(s_day.charAt(0) == 1)
{
word_day = "first";
}
else if(s_day.charAt(0) == 2)
{
word_day = "second";
}
else if(s_day.charAt(0) == 3)
{
word_day = "third";
}
else if(s_day.charAt(0) == 4)
{
word_day = "fourth";
}
else if(s_day.charAt(0) == 5)
{
word_day = "fifth";
}
else if(s_day.charAt(0) == 6)
{
word_day = "sixth";
}
else if(s_day.charAt(0) == 7)
{
word_day = "seventh";
}
else if(s_day.charAt(0) == 8)
{
word_day = "eighth";
}
else if(s_day.charAt(0) == 9)
{
word_day = "ninth";
}
break;
case 2:
//teens
if(s_day.charAt(0) == 1 && s_day.charAt(1) == 0)
{
word_day = "tenth";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 1)
{
word_day = "eleventh";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 2)
{
word_day = "twelfth";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 3)
{
word_day = "thirteenth";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 4)
{
word_day = "fourteenth";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 5)
{
word_day = "fifteenth";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 6)
{
word_day = "sixteenth";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 7)
{
word_day = "seventeenth";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 8)
{
word_day = "eighteenth";
}
else if(s_day.charAt(0) == 1 && s_day.charAt(1) == 9)
{
word_day = "ninteenth";
}
//twenties
if(s_day.charAt(0) == 2 && s_day.charAt(1) == 0)
{
word_day = "twentieth";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 1)
{
word_day = "twenty-first";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 2)
{
word_day = "twenty-second";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 3)
{
word_day = "twenty-third";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 4)
{
word_day = "twenty-fourth";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 5)
{
word_day = "twenty-fifth";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 6)
{
word_day = "twenty-sixth";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 7)
{
word_day = "twenty-seventh";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 8)
{
word_day = "twenty-eighth";
}
else if(s_day.charAt(0) == 2 && s_day.charAt(1) == 9)
{
word_day = "twenty-ninth";
}
//thirties
if(s_day.charAt(0) == 3 && s_day.charAt(1) == 0)
{
word_day = "thirtieth";
}
else if(s_day.charAt(0) == 3 && s_day.charAt(1) == 1)
{
word_day = "thirty-first";
}
break;
}
System.out.println("Your birthday is: " + s_month + " "+ word_day);
}
最佳答案
每次比较字符时,您做错了。
s_day.charAt(0) == 1
应该
s_day.charAt(0) == '1'
但这甚至比需要的还要复杂。您在变量
int
中将日期作为day
,对吗?那么,为什么不基于此做出一个if
语句呢?if (day == 1) {
word_day = "first";
}else if (day == 2)
//and so on