gpt4 book ai didi

java - 错误: variable digitMonth might not have been initialized

转载 作者:行者123 更新时间:2023-12-01 12:33:17 29 4
gpt4 key购买 nike

我正在尝试编写一个程序,该程序需要出生年、月、日,并计算生日所在的那一天。问题是,我收到此错误消息:

错误:变量digitMonth可能尚未初始化 总计=输入年份+测试2+数字月份+输入日期; ^

我不知道如何解决它。将digitMonth设置为一个数字(例如1)使程序可以运行,但是对于公式,每个月都需要不同的数字(1代表一月,4代表二月,4代表三月,0代表四月,等等)

我已经查看了其他问题中是否存在此类错误,但尚未发现任何有用的内容。

帮忙?

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");
}
}

}

最佳答案

您只能在 ifelse if 语句中为 digitMonth 赋值,而不是在最后的 else 中赋值> 声明。
那么,如果 ifelse if 都没有成功,而只有 else 部分成功,会发生什么呢?
的那么 digitMonth 的值是多少?

答案:

这可能永远不会在您的代码中发生,但编译器仍然会提示它。

有两种解决方案:

1) 只需为 digitMonth 指定一个初始值即可。即int digitalMonth = 0;

2) 在最后的 else 中初始化 digitMonth。即:

else{
//some code
digitMonth = 0;
}

希望这有帮助

关于java - 错误: variable digitMonth might not have been initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25774027/

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