任何人都可以告诉我为什么它给我变量未初始化?

时间:2015-01-29 18:02:26

标签: java if-statement

每次我尝试编译它时都会显示d1变量可能未初始化。我认为问题可能在else if。告诉我如何在else if中运行2个语句。

import java.util.Scanner;
class IDC {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("                        ");
        System.out.println("Input ID card no...");

        String x = scan.next();


        x = x.substring(0, x.length() - 1); //removing the last char of the string

        String CardNo = x;

        String y = x = x.substring(0, x.length() - 7); //birthday

        y = "19" + y; //birth year = y




        String CardNO1 = CardNo.substring(0, CardNo.length() - 4);

        //System.out.println(CardNO1);

        CardNO1 = CardNO1.substring(2);

        //System.out.println(CardNO1);

        //gender

        int g = Integer.parseInt(CardNO1); //converting string to int
        String G;
        if (g < 500) {
            G = "Male";
        } else {
            G = "female";
        }
        //System.out.println(G);
        double C = Integer.parseInt(CardNO1);
        if (C > 500) {
            C = C - 500;
        } else {
            C = C;
        }
        //calculating month and the day of birth

        double d1;
        int Month;
        //

        if (C < 31) {
            Month = 1;
            d1 = C;
        } else if (C <= 60) {
            Month = 2;
            d1 = C - 31;
        } else if (C <= 91) {
            Month = 3;
            d1 = C - 60;
        } else if (C <= 121) {
            Month = 4;
            d1 = C - 91;
        } else if (C <= 152) {
            Month = 5;
            d1 = C - 121;
        } else if (C <= 182) {
            Month = 6;
            d1 = C - 152;
        } else if (C <= 213) {
            Month = 7;
            d1 = C - 182;
        } else if (C <= 244) {
            Month = 8;
            d1 = C - 213;
        } else if (C <= 274) {
            Month = 9;
            d1 = C - 244;
        } else if (C <= 305) {
            Month = 10;
            d1 = C - 274;
        } else if (C <= 335) {
            Month = 11;
            d1 = C - 305;
        } else if (C <= 366) {
            Month = 12;
            d1 = C - 335;
        } else {
            Month = 00;
        }
        //double d1;

        System.out.println("                        ");

        System.out.println("Your Birthday...  ");
        System.out.println("Date.." + d1);
        System.out.print("Month.. " + Month);
        System.out.println("  Year.. " + y);

        System.out.println("                        ");

        System.out.println("Your Gender...");
        System.out.println(G);

    }

}

1 个答案:

答案 0 :(得分:1)

d1未在else块中初始化,仅在if或else if块中初始化,因此如果if()和else if()块中的所有语句都为false,则控制器将转到else块,其中d1仍未初始化。所以当你尝试在system.out.println()中访问它时,编译器会正确地抛出错误。您可能希望在开始时将值初始化为0.