我正試圖編寫一個程序,該程序需要出生年份,月份和日期,並計算哪一天說的生日說謊。事情是,我收到此錯誤消息:錯誤:變量digitMonth可能未被初始化
錯誤:變量digitMonth可能未初始化 total = 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");
}
}
}
爲什麼你使用'inputMonth> 0 && inputMonth <2 '而不是'inputMonth == 1'? (這將很容易讓你把'if'轉換成'switch'作爲獎勵)。 – Keppil 2014-09-10 19:59:51
在Java可以* 100%確定*它已被初始化之前,您使用'digitMonth'。在'else'分支中設置'digitMonth',或者退出該方法。 (或將一個默認值賦給'digitMonth') – August 2014-09-10 20:00:53