无法弄清楚为什么某些变量无法初始化

时间:2018-12-03 19:29:18

标签: java compiler-errors return

public static String produceAnswer(String y) {
    int space1Location = y.indexOf(" ");
    String value1 = y.substring(0, space1Location - 1);
    String value2 = y.substring(space1Location + 3);
    String operator = y.substring(space1Location + 1, space1Location + 2);
    int underLocation = value2.indexOf("_");
    int slashLocation = value2.indexOf("/");
    String wholeNum;
    String numerator;
    String denominator;
    if(underLocation != -1) {
        wholeNum = value2.substring(0, underLocation);
        numerator = value2.substring(underLocation + 1, slashLocation);
        denominator = value2.substring(slashLocation + 1);
    }
    else if(underLocation == -1 && slashLocation != -1) {
        numerator = value2.substring(0, slashLocation);
        denominator = value2.substring(slashLocation + 1);
        wholeNum = "0";
    }
    else if(underLocation == -1 && slashLocation == -1) {
        wholeNum = value2;
        numerator = "0";
        denominator = "1";
    }
    return "whole:" + wholeNum + " numerator:" + numerator + " denominator:" + denominator;
}

由于某些原因,我的代码中的return语句不起作用。它说变量没有被初始化,这对我来说没有意义,因为我肯定在if语句中对它们进行了初始化吗?怎么了?

1 个答案:

答案 0 :(得分:6)

在编写不带最终if-else-if...的{​​{1}}语句时,编译器不知道是否保证其中一个条件为else,这意味着它不知道确保您的局部变量将被初始化。

您应将最后一个true更改为else if

else

甚至:

if(underLocation != -1) {
    wholeNum = value2.substring(0, underLocation);
    numerator = value2.substring(underLocation + 1, slashLocation);
    denominator = value2.substring(slashLocation + 1);
} else if (underLocation == -1 && slashLocation != -1) {
    numerator = value2.substring(0, slashLocation);
    denominator = value2.substring(slashLocation + 1);
    wholeNum = "0";
} else {
    wholeNum = value2;
    numerator = "0";
    denominator = "1";
}

由于第一个条件为if (underLocation != -1) { wholeNum = value2.substring(0, underLocation); numerator = value2.substring(underLocation + 1, slashLocation); denominator = value2.substring(slashLocation + 1); } else if (slashLocation != -1) { numerator = value2.substring(0, slashLocation); denominator = value2.substring(slashLocation + 1); wholeNum = "0"; } else { wholeNum = value2; numerator = "0"; denominator = "1"; } ,因此我们已经知道在第二个条件下保证falseunderLocation,因此测试-1就足够了。