我正在尝试编写一个程序,该程序需要出生的年,月和日,并计算出表示生日的日期。问题是,我收到此错误消息:
错误:变量digitMonth可能尚未初始化
总计= inputYear + test2 + digitMonth + inputDay;
^
我不知道该如何解决。将digitMonth设置为数字(例如1)可以使程序正常工作,但是对于公式,每个月都需要一个不同的数字(1表示1月,4表示2月,4表示3月,0表示4月,等等)。
我已经查看了其他类似问题的问题,但还没有发现有用的信息。
帮帮我?
import java.util.Scanner;
public class Birth{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int inputYear, inputMonth, inputDay, digitMonth, test2, total, dayNum;
System.out.println("Enter the last two digits of the year that you were born in");
inputYear = scan.nextInt();
System.out.println("Enter the month number that your were born in");
inputMonth = scan.nextInt();
System.out.println("Enter your birth day");
inputDay = scan.nextInt();
test2 = inputYear / 4;
if (inputMonth > 0 && inputMonth < 2)
{
digitMonth = 1;
}
else if (inputMonth > 1 && inputMonth < 3)
{
digitMonth = 4;
}
else if (inputMonth > 2 && inputMonth < 4)
{
digitMonth = 4;
}
else if (inputMonth > 3 && inputMonth < 5)
{
digitMonth = 0;
}
else if (inputMonth > 4 && inputMonth < 6)
{
digitMonth = 2;
}
else if (inputMonth > 5 && inputMonth < 7)
{
digitMonth = 5;
}
else if (inputMonth > 6 && inputMonth < 8)
{
digitMonth = 0;
}
else if (inputMonth > 7 && inputMonth < 9)
{
digitMonth = 3;
}
else if (inputMonth > 8 && inputMonth < 10)
{
digitMonth = 6;
}
else if (inputMonth > 9 && inputMonth < 11)
{
digitMonth = 1;
}
else if (inputMonth > 10 && inputMonth < 12)
{
digitMonth = 4;
}
else if (inputMonth > 11 && inputMonth < 13)
{
digitMonth = 6;
}
else
System.out.println("You fuck-up");
total = inputYear + test2 + digitMonth + inputDay;
dayNum = total / 7;
if (dayNum > 0 || dayNum < 2)
{
System.out.println("You were born on a Sunday");
}
else if (dayNum > 1 || dayNum < 3)
{
System.out.println("You were born on a Monday");
}
else if (dayNum > 2 || dayNum < 4)
{
System.out.println("You were born on a Tuesday");
}
else if (dayNum > 3 || dayNum < 5)
{
System.out.println("You were born on a Wednesday");
}
else if (dayNum > 4 || dayNum < 6)
{
System.out.println("You were born on a Thursday");
}
else if (dayNum > 5 || dayNum < 7)
{
System.out.println("You were born on a Friday");
}
else if (dayNum > -1 || dayNum < 1)
{
System.out.println("You were born on a Saturday");
}
}
}
最佳答案
您只能在digitMonth
和if
语句内为else if
分配一个值,而不是在最终的else
语句上。
那么,如果if
和else if
都没有成功而只有else
部分成功了,会发生什么呢?的
那么digitMonth
的值是多少?答:无
这可能永远不会在您的代码中发生,但是编译器会抱怨它。
有两种解决方案:
1)只需给digitMonth
一个初始值。即int digitMonth = 0;
2)在最后一个else中初始化digitMonth
。即:
else{
//some code
digitMonth = 0;
}
希望这可以帮助